如何使用一个带有几个子节点的根节点创建一个json树

时间:2013-10-31 12:28:42

标签: java json

我创建了一个json,它有一个根节点,有几个子节点使用java现在我要求root下的子节点也可能有一些孩子。但是我无法做到。这就是我的意思到目前为止已经做了....

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"
    }
  ]
}

1 个答案:

答案 0 :(得分:1)

我对你的代码感到有些困惑,但有些事情对我很清楚:你想要得到什么。因此,从头开始,我创建了一些您可以复制和运行的代码,以了解如何获得所需的JSON。

元素的顺序可能对你很重要(注意在JSON对象中,键的顺序并不重要 - 是一个地图! - ),所以我编辑了一些不是纯粹的Gson做事的代码,但是正是你的榜样。

package stackoverflow.questions;

import java.lang.reflect.Field;
import java.util.*;

import com.google.gson.*;

public class JsonApplication {

   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);

   }
}

这是执行:

{"name":"Culture",[{"name":"Salary"},{"name":"Work"},{"name":"Effort"}],"name":"Work",[{"name":"Culture"},{"name":"Work"}]}