BlueShark
BlueShark

Reputation: 547

How to create a json tree with one root node with couple of child nodes

I have created a json which have a root node with couple of child nodes using java now i have a requirement that the child node under the root may also have some children.But i am unable to do that.Here is what i have done so far....

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

This is the json output i am getting

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

But i need

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

Upvotes: 0

Views: 3004

Answers (1)

giampaolo
giampaolo

Reputation: 6934

I'm a bit confused by your code, but something is clear to me: what you want to get. So starting from scratch I created some code you can copy&run to see how you can get your desired JSON.

Probably the order of elements is important for you (pay attention that in JSON object order of keys is not important -is a map!-), so I edited some code that is not pure Gson way of doing things but that creates exactly your example.

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

   }
}

and this is the execution:

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

Upvotes: 1

Related Questions