我创建了一个 json,它有一个根节点和几个使用 java 的子节点现在我要求根下的子节点也可能有一些子节点。但我无法做到这一点。这就是我所做的远的....
class Entry {
private String name;
public String getChildren() {
return name;
}
public void setChildren(String name) {
this.name = name;
}
}
public class JsonApplication {
public static void main(String[] args) {
// TODO code application logic here
String arr[] = {"Culture", "Salary", "Work", "Effort"};
EntryListContainer entryListContainer = new EntryListContainer();
List<Entry> entryList1 = new ArrayList<>();
List<Entry> entryList2 = new ArrayList<>();
for (int i = 0; i < arr.length; i++) {
Entry entry1 = new Entry();
entry1.setChildren(arr[i]);
entryList1.add(entry1);
entryList2.add(entry1);
/*Child nodes are created here and put into entryListContainer*/
entryListContainer.setEntryList1(entryList1);
entryListContainer.setEntryList1(entryList2);
}
/*Root node this will collapse and get back to Original position on click*/
entryListContainer.setName("Employee");
entryListContainer.setName("Culture");
Map<String, String> mapping = new HashMap<>();
mapping.put("entryList1", "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> 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;
}
}
这是我得到的 json 输出
{
"children": [
{
"name":"Culture"
},
{
"name":"Salary"
},
{
"name":"Work"
},
{
"name":"Effort"
}
],
"name":"Employee"
}
但是我需要
{
"name":"Culture",
"children":[
{
"name":"Culture"
},
{
"name":"Salary"
},
{
"name":"Work"
},
{
"name":"Effort"
}
],
"name":"Work",
"children" : [
{
"name":"Culture"
},
{
"name":"Work"
}
]
}