I have to make a Json which will form a tree like structure.I have written a java code that is forming a structure like that but it does not satisfy the purpose.Here where i have done so far..This is my java class..
import com.google.gson.FieldNamingStrategy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class GsonProgram {
public static void main(String... args) throws Exception {
String arr[] = {"Culture", "Salary", "Work", "Effort"};
EntryListContainer entryListContainer = new EntryListContainer();
List<Entry> entryList1 = new ArrayList<>();
for (int i = 0; i < arr.length; i++) {
Entry entry1 = new Entry();
Entry entry2 = new Entry();
entry1.setChildren(arr[i]);
entryList1.add(entry1);
entryList2.add(entry2);
entryListContainer.setEntryList1(entryList1);
entryListContainer.setEntryList1(entryList2);
/*Root node this will collapse and get back to Original position on click*/
entryListContainer.setName("Employee");
entryListContainer.setName("manager");
}
Map<String, String> mapping = new HashMap<>();
mapping.put("entryList1", "name");
mapping.put("entryList2", "name");
Gson gson = new GsonBuilder().serializeNulls().setFieldNamingStrategy(new DynamicFieldNamingStrategy(mapping)).create();
System.out.println(gson.toJson(entryListContainer));
}
}
class DynamicFieldNamingStrategy implements FieldNamingStrategy {
private Map<String, String> mapping;
public DynamicFieldNamingStrategy(Map<String, String> mapping) {
this.mapping = mapping;
}
#Override
public String translateName(Field field) {
String newName = mapping.get(field.getName());
if (newName != null) {
return newName;
}
return field.getName();
}
}
class EntryListContainer {
private List<Entry> entryList1;
public void setEntryList1(List<Entry> entryList1) {
this.entryList1 = entryList1;
}
public List<Entry> getEntryList1() {
return entryList1;
}
}
class Entry {
private String name;
public String getChildren() {
return name;
}
public void setChildren(String name) {
this.name = name;
}
}
and this is the generated json
{
"name":[{
"name":"Salary"
},{
"name":"Salary"
},{
"name":"Work"
},{
"name":"Doller"
}]
}
But i want this structure...
{
"name":"Employee",
"children":[{
"name":"Salary"
},{
"name":"Salary"
},{
"name":"Work"
},{
"name":"Doller"
}]
}
I need this format of json.somebody please help....
The pseudo class structure should be:
class DynamicFieldNamingStrategy{
private String name;
private List<Entry> children;
}
GsonProgram
public class GsonProgram {
public static void main(String... args) throws Exception {
Entry entry1 = new Entry();
entry1.setChildren("Salary");
Entry entry2 = new Entry();
entry2.setChildren("Salary");
Entry entry3 = new Entry();
entry3.setChildren("Work");
Entry entry4 = new Entry();
entry4.setChildren("Doller");
EntryListContainer entryListContainer = new EntryListContainer();
ArrayList<Entry> entryList1 = new ArrayList<Entry>();
entryList1.add(entry1);
entryList1.add(entry2);
entryList1.add(entry3);
entryList1.add(entry4);
entryListContainer.setEntryList1(entryList1);
entryListContainer.setName("Employee");
Map<String, String> mapping = new HashMap<String, String>();
mapping.put("entryList1", "name");
Gson gson = new GsonBuilder().serializeNulls().setFieldNamingStrategy(new DynamicFieldNamingStrategy(mapping)).create();
System.out.println(gson.toJson(entryListContainer));
}
}
EntryListContainer
class EntryListContainer {
private List<Entry> children;
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setEntryList1(List<Entry> entryList1) {
this.children = entryList1;
}
public List<Entry> getEntryList1() {
return children;
}
}
Output:
{
"children": [
{
"name": "Salary"
},
{
"name": "Salary"
},
{
"name": "Work"
},
{
"name": "Doller"
}
],
"name": "Employee"
}
Related
Kindly help me to get the subnodes list inside bom attributes
JSON file
[
{
"subConfigId":"bac",
"totalPrice":"634.00",
"bom":{
"ucid":"ucid",
"type":"RootNode",
"attributes":{
"visible":true,
"price_status":"SUCCESS"
},
"subnodes":[
{
"description":"Enterprise Shock Rack",
"ucid":"ucid"
},
{
"description":"SVC",
"ucid":"ucid"
}
]
},
"breakdown":{
"SV":550.0,
"HW":6084.0
},
"currency":"USD"
}
]
GsonNodes.java
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
public class GsonNodes {
public static void main(String[] args) throws IOException {
try{
JsonElement je = new JsonParser().parse(new FileReader(
"C:/Desktop/json.txt"));
JsonArray ja = je.getAsJsonArray();
Iterator itr = ja.iterator();
while(itr.hasNext()){
JsonElement je1 = (JsonElement) itr.next();
Gson gson = new Gson();
Details details = gson.fromJson(je1, Details.class);
System.out.println(details.getSubConfigId());
System.out.println(details.getCurrency());
System.out.println(details.getBreakdown());
System.out.println(details.getTotalPrice());
System.out.println(details.getBom().getUcid());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Details.java POJO
import java.io.Serializable;
import java.util.Map;
public class Details implements Serializable{
private String subConfigId;
private String totalPrice;
private Bom bom;
private String currency;
private Map<String, String> breakdown;
public String getSubConfigId() {
return subConfigId;
}
public void setSubConfigId(String subConfigId) {
this.subConfigId = subConfigId;
}
public String getTotalPrice() {
return totalPrice;
}
public void setTotalPrice(String totalPrice) {
this.totalPrice = totalPrice;
}
public Bom getBom() {
return bom;
}
public void setBom(Bom bom) {
this.bom = bom;
}
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
public Map<String, String> getBreakdown() {
return breakdown;
}
public void setBreakdown(Map<String, String> breakdown) {
this.breakdown = breakdown;
}
}
Bom.java
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class Bom implements Serializable{
private String ucid;
private String type;
private Map<String, String> attributes;
private List<Subnodes> subnodes = new ArrayList<Subnodes>();
public String getUcid() {
return ucid;
}
public void setUcid(String ucid) {
this.ucid = ucid;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Map<String, String> getAttributes() {
return attributes;
}
public void setAttributes(Map<String, String> attributes) {
this.attributes = attributes;
}
#Override
public String toString(){
return getUcid() + ", "+getType()+", "+getAttributes();
}
}
Subnodes.java
import java.io.Serializable;
import java.util.Map;
public class Subnodes implements Serializable{
private String description;
private String ucid;
private Map<String, String> attributes;
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getUcid() {
return ucid;
}
public void setUcid(String ucid) {
this.ucid = ucid;
}
public Map<String, String> getAttributes() {
return attributes;
}
public void setAttributes(Map<String, String> attributes) {
this.attributes = attributes;
}
}
I am getting an error , when i try to get the "subnodes"
I added the following code in the class
private List<Subnodes> subnodes = new ArrayList<Subnodes>();
then i am getting the error "Expected STRING but was BEGIN_ARRAY"
kindly help me that how can i get the "subnodes" list
In Bom.java
Please add a getter/setter method for :
private List<Subnodes> subnodes = new ArrayList<Subnodes>();
public List<Subnodes> getSubnodes() {
return subnodes;
}
public void setSubnodes(List<Subnodes> subnodes) {
this.subnodes = subnodes;
}
i have tried as below .. this is working fine.
package com.brp.mvc.util;
import java.io.IOException;
import java.util.Iterator;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
public class GsonNodes {
public static void main(String[] args) throws IOException {
try {
JsonElement je = new JsonParser().parse("[{\"subConfigId\":\"bac\",\"totalPrice\":\"634.00\",\"bom\":{\"ucid\":\"ucid\",\"type\":\"RootNode\",\"attributes\":{\"visible\":true,\"price_status\":\"SUCCESS\"},\"subnodes\":[{\"description\":\"Enterprise Shock Rack\",\"ucid\":\"ucid\"},{\"description\":\"SVC\",\"ucid\":\"ucid\"}]},\"breakdown\":{\"SV\":550.0,\"HW\":6084.0},\"currency\":\"USD\"}]");
JsonArray ja = je.getAsJsonArray();
Iterator itr = ja.iterator();
while (itr.hasNext()) {
JsonElement je1 = (JsonElement) itr.next();
Gson gson = new Gson();
Details details = gson.fromJson(je1, Details.class);
System.out.println(details.getSubConfigId());
System.out.println(details.getCurrency());
System.out.println(details.getBreakdown());
System.out.println(details.getTotalPrice());
System.out.println(details.getBom().getUcid());
System.out.println(details.getBom().getSubnodes().get(0).getDescription());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
i have added one method to convert json into string as below :
public static String readFile(String filename) {
String result = "";
try {
BufferedReader br = new BufferedReader(new FileReader(filename));
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
line = br.readLine();
}
result = sb.toString();
} catch(Exception e) {
e.printStackTrace();
}
return result;
}
and use this method like below :
JsonElement je = new JsonParser().parse(readFile("C:/Desktop/json.txt"));
I have to map a json which would look like this, it's basicly an object, which can contain the same object again as a child, then that one can also contain the same object again. How would i be able to map this to java pojo's?
This is the json:
{
"group": [
{
"name": "Beheerders",
"desc": "Beheerders",
"children" : [
"group" : [
{
"name": "Beheerders",
"desc": "Beheerders"
},
{
"name": "Beheerders",
"desc": "Beheerders"
},
{
"name": "Beheerders",
"desc": "Beheerders"
"children": [
"group" : [
{
"name": "Beheerders",
"desc": "Beheerders"
},
{
"name": "Beheerders",
"desc": "Beheerders"
}
}
}
]
}
And i have these 4 pojo's:
Group.java
private String name;
private String desc;
private Children children;
//getters & Setters & toString
GroupList.java
private ArrayList<Group> group;
public void setGroup(ArrayList<Group> group) {
this.group = group;
}
public ArrayList<Group> getGroup() {
return this.group;
}
Children.java
private ArrayList<ChildrenGroup> group;
public ArrayList<ChildrenGroup> getGroup() {
return this.group;
}
public void setGroup(ArrayList<ChildrenGroup> group) {
this.group = group;
}
childrengroup.java
private String name;
private String desc;
private Children Children;
//Getters & Setters & toString
This is not working for me, i always get this error:
com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.util.ArrayList out of START_OBJECT token
Your JSON is not valid and your objects aren't correctly using object vs List. Please validate your example JSON. "children" : [ "group" : [ is invalid.
Your errors are occurring because it is encountering [ when your java objects are specifying {.
You can remove Children and ChildrenGroup and just nest GroupList inside Group as well.
You can use online tools like jsonschema2pojo to generate POJO from your JSON.
If I'm understanding correctly you are trying to convert smth like the following:
{
"g":[
{
"a":"1",
"c":"2"
},
{
"a":"2",
"c":"3",
"d":[
{
"g":[
{"a":"3",
"c":"4"},
{"a":"5",
"c":"6"}
]
}
]
}
]
}
The output for this one will be:
-----------------------------------com.example.D.java-----------------------------------
package com.example;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class D {
private List<G_> g = null;
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
public List<G_> getG() {
return g;
}
public void setG(List<G_> g) {
this.g = g;
}
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
-----------------------------------com.example.Example.java-----------------------------------
package com.example;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Example {
private List<G> g = null;
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
public List<G> getG() {
return g;
}
public void setG(List<G> g) {
this.g = g;
}
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
-----------------------------------com.example.G.java-----------------------------------
package com.example;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class G {
private String a;
private String c;
private List<D> d = null;
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
public String getA() {
return a;
}
public void setA(String a) {
this.a = a;
}
public String getC() {
return c;
}
public void setC(String c) {
this.c = c;
}
public List<D> getD() {
return d;
}
public void setD(List<D> d) {
this.d = d;
}
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
-----------------------------------com.example.G_.java-----------------------------------
package com.example;
import java.util.HashMap;
import java.util.Map;
public class G_ {
private String a;
private String c;
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
public String getA() {
return a;
}
public void setA(String a) {
this.a = a;
}
public String getC() {
return c;
}
public void setC(String c) {
this.c = c;
}
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
I am trying to get java object from dynamic JSON.
One Important point these given classes are from third party API.
#JsonTypeInfo(
use = Id.NAME,
include = As.PROPERTY,
property = "nodeType"
)
#JsonSubTypes({ #Type(
name = "Filter",
value = Filter.class
), #Type(
name = "Criterion",
value = Criterion.class
)})
public abstract class Node {
public Node() {
}
#JsonIgnore
public EvaluationResult evaluate(Map<UUID, List<AnswerValue>> answers) {
Evaluator evaluator = new Evaluator();
return evaluator.evaluateAdvancedLogic(this, answers);
}
}
Filter.java
#JsonInclude(Include.NON_NULL)
#JsonPropertyOrder({"evaluationType", "filters"})
public class Filter extends Node {
#JsonProperty("evaluationType")
private EvaluationType evaluationType;
#NotNull
#JsonProperty("filters")
#Valid
private List<Node> filters = new ArrayList();
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap();
public Filter() {
}
#JsonProperty("evaluationType")
public EvaluationType getEvaluationType() {
return this.evaluationType;
}
#JsonProperty("evaluationType")
public void setEvaluationType(EvaluationType evaluationType) {
this.evaluationType = evaluationType;
}
#JsonProperty("filters")
public List<Node> getFilters() {
return this.filters;
}
#JsonProperty("filters")
public void setFilters(List<Node> filters) {
this.filters = filters;
}
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
#JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
}
Criterion.java
#JsonInclude(Include.NON_NULL)
#JsonPropertyOrder({"fieldSourceType", "fieldCategoryName", "sequenceNumber", "fieldName", "values", "operator", "fieldId"})
public class Criterion extends Node {
#JsonProperty("fieldSourceType")
private FieldSourceType fieldSourceType;
#JsonProperty("fieldCategoryName")
private String fieldCategoryName;
#NotNull
#JsonProperty("sequenceNumber")
private Long sequenceNumber;
#JsonProperty("fieldName")
private String fieldName;
#JsonProperty("values")
#Valid
private List<String> values = new ArrayList();
#JsonProperty("operator")
#Valid
private Operator operator;
#NotNull
#JsonProperty("fieldId")
private UUID fieldId;
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap();
public Criterion() {
}
#JsonProperty("fieldSourceType")
public FieldSourceType getFieldSourceType() {
return this.fieldSourceType;
}
#JsonProperty("fieldSourceType")
public void setFieldSourceType(FieldSourceType fieldSourceType) {
this.fieldSourceType = fieldSourceType;
}
#JsonProperty("fieldCategoryName")
public String getFieldCategoryName() {
return this.fieldCategoryName;
}
#JsonProperty("fieldCategoryName")
public void setFieldCategoryName(String fieldCategoryName) {
this.fieldCategoryName = fieldCategoryName;
}
#JsonProperty("sequenceNumber")
public Long getSequenceNumber() {
return this.sequenceNumber;
}
#JsonProperty("sequenceNumber")
public void setSequenceNumber(Long sequenceNumber) {
this.sequenceNumber = sequenceNumber;
}
#JsonProperty("fieldName")
public String getFieldName() {
return this.fieldName;
}
#JsonProperty("fieldName")
public void setFieldName(String fieldName) {
this.fieldName = fieldName;
}
#JsonProperty("values")
public List<String> getValues() {
return this.values;
}
#JsonProperty("values")
public void setValues(List<String> values) {
this.values = values;
}
#JsonProperty("operator")
public Operator getOperator() {
return this.operator;
}
#JsonProperty("operator")
public void setOperator(Operator operator) {
this.operator = operator;
}
#JsonProperty("fieldId")
public UUID getFieldId() {
return this.fieldId;
}
#JsonProperty("fieldId")
public void setFieldId(UUID fieldId) {
this.fieldId = fieldId;
}
}
The json used to conversion is this.
{
"evaluationType":"AND",
"nodeType":"Criterion",
"Criterion":[
{
"fieldName":"sdada",
"values":"sdad",
"operator":{
"operatorType":"Equals"
}
},
{
"nodeType":"Criterion",
"fieldName":"dasa",
"values":"das",
"operator":{
"operatorType":"Equals"
}
},
{
"nodeType":"Criterion",
"fieldName":"dada",
"values":"dads",
"operator":{
"operatorType":"Equals"
}
}
]
}
The problem is that deserialization of this JSON fails with following error:
{
"message": "Class com.cvent.logic.model.Criterion is not assignable to com.cvent.logic.model.Filter"
}
The first part of the JSON is wrong
{
"evaluationType":"AND",
"nodeType":"Criterion",
"Criterion":[
It says that the type is Criterion but it has evaluationType from Filter.
Also, probably "Criterion" : [ should be "filters" : [
I have to make a tree like JSON structure with Java where I have a parent node with multiple children in it and so on. This is my code I have partially done this one but not completely successful to do it ..here is the output I need
{
"name": "Culture",
"children": [
{
"name": "Salary"
},
{
"name": "Work",
"children": [
{
"name": "Effort"
},
{
"name": "trust"
}
]
}
]
}
but what I am generating is
{"name":"Culture",[{"name":"Salary"},{"name":"Work"},{"name":"Effort"}],"name":"Work",[{"name":"Culture"},{"name":"Work"}]}
Here is my code:
import com.google.gson.Gson;
import java.util.ArrayList;
import java.util.List;
public class ParentChildApp {
public static class EntryListContainer {
public List<Entry> children = new ArrayList<Entry>();
public Entry name;
}
public static class Entry {
private String name;
public Entry(String name) {
this.name = name;
}
}
public static void main(String[] args) {
EntryListContainer elc1 = new EntryListContainer();
elc1.name = new Entry("Culture");
elc1.children.add(new Entry("Salary"));
elc1.children.add(new Entry("Work"));
elc1.children.add(new Entry("Effort"));
EntryListContainer elc2 = new EntryListContainer();
elc2.name = new Entry("Work");
elc2.children.add(new Entry("Culture"));
elc2.children.add(new Entry("Work"));
ArrayList<EntryListContainer> al = new ArrayList<EntryListContainer>();
Gson g = new Gson();
al.add(elc1);
al.add(elc2);
StringBuilder sb = new StringBuilder("{");
for (EntryListContainer elc : al) {
sb.append(g.toJson(elc.name).replace("{", "").replace("}", ""));
sb.append(",");
sb.append(g.toJson(elc.children));
sb.append(",");
}
String partialJson = sb.toString();
if (al.size() > 1) {
int c = partialJson.lastIndexOf(",");
partialJson = partialJson.substring(0, c);
}
String finalJson = partialJson + "}";
System.out.println(finalJson);
}
}
Do this:
package stackoverflow.questions;
import com.google.gson.*;
import java.util.ArrayList;
import java.util.List;
public class ParentChildApp {
public static class Entry {
private String name;
public Entry(String name) {
this.name = name;
}
private List<Entry> children;
public void add(Entry node){
if (children == null)
children = new ArrayList<Entry>();
children.add(node);
}
}
public static void main(String[] args) {
Entry workNode = new Entry("Work");
workNode.add(new Entry("Effort"));
workNode.add(new Entry("Trust"));
Entry salaryNode = new Entry("Salary");
Entry cultureNode = new Entry("Culture");
cultureNode.add(salaryNode);
cultureNode.add(workNode);
Gson g = new Gson();
System.out.println(g.toJson(cultureNode));
}
}
You will get exactly the JSON you are looking for.
I am new to json. I am able to create a json from servlet. But I am bounded to create a json like below-
{
"name":"Employee",
"children":[{
"name":"Subho"
},
{
"name":"jeet",
"children":[{
"name":"rahul"
},
{
"name":"abhijit"
}]
}]
}
But what I create is like-
{
"children":[
{"name":"Culture"},
{"name":"Salary"},
{"name":"Work"},
{"name":"Economy"}
],
"name":"Employee"
}
My servlet code is-
public class ActionServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
Random r = new Random();
int low = 0;
int high = 5;
int R = r.nextInt(high - low) + low;
/*Sample data for child nodes actual data will be called here*/
String arr[] = {"Culture", "Salary", "Work", "Economy"};
/*Responsible for creation of the child nodes and their names */
Map<String, String> mapping = new HashMap<String, String>();
EntryListContainer entryListContainer = new EntryListContainer();
List<Entry> entryList1 = new ArrayList<Entry>();
for (int i = 0; i < R; i++) {
/*Model object for the Link*/
Entry entry1 = new Entry();
entry1.setChildren(arr[i]);
entryList1.add(entry1);
}
entryListContainer.setEntryList1(entryList1);
/*Root node this will collapse and get back to Original position on click*/
entryListContainer.setName("Employee");
mapping.put("entryList1","name");
Gson gson = new GsonBuilder().serializeNulls().setFieldNamingStrategy(new DynamicFieldNamingStrategy(mapping)).create();
System.out.println(gson.toJson(entryListContainer));
String json = null;
/*conversion of the json from the generated java object*/
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
json = new Gson().toJson(gson);
System.out.println(json);
response.getWriter().write(gson.toJson(entryListContainer));
} catch (Exception e) {
e.printStackTrace();
} finally {
out.close();
}
}
This is the EntryListContainer class
public class EntryListContainer {
private List<Entry> children;
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setEntryList1(List<Entry> entryList1) {
this.children = entryList1;
}
public List<Entry> getEntryList1() {
return children;
}
This is the DynamicFieldNamingStrategy class
public class DynamicFieldNamingStrategy implements FieldNamingStrategy{
private Map<String, String> mapping;
public DynamicFieldNamingStrategy(Map<String, String> mapping) {
this.mapping = mapping;
}
#Override
public String translateName(Field field) {
String newName = mapping.get(field.getName());
if (newName != null) {
return newName;
}
return field.getName();
}
This servlet code is creating a json. Here 1st I create all the children nodes and put them in a list (here entryList1), and then put them in a hashmap. But what I create is not fulfilling my requirement..
Please anyone help me with this..
If we will put your JSon to jsoneditoronline, we get:
{
"name": "Employee",
"children": [
{
"name": "Subho"
},
{
"name": "jeet",
"children": [
{
"name": "rahul"
},
{
"name": "abhijit"
}
]
}
]
}
Now we can see that each Node has name and list of other Nodes:
Node
public class Node {
private String name = "";
private List<Node> children;
public List<Node> getChildren() {
return children;
}
public void setChildren(List<Node> children) {
this.children = children;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Code
Node child = new Node();
child.setName("Employee");
List<Node> list = new ArrayList<Node>();
Node subChild = new Node();
subChild.setName("Subho");
list.add(subChild);
subChild = new Node();
subChild.setName("jeet");
List<Node> sublist = new ArrayList<Node>();
Node subsubChild = new Node();
subsubChild.setName("Subho");
sublist.add(subsubChild);
subsubChild = new Node();
subsubChild.setName("Subho");
sublist.add(subsubChild);
subChild.setChildren(sublist);
list.add(subChild);
child.setChildren(list);
Gson gson = new Gson();
String output = gson.toJson(child);
Output:
{"name":"Employee","children":[{"name":"Subho"},{"name":"jeet","children":[{"name":"Subho"},{"name":"Subho"}]}]}