Search code examples
javajsonjson-simple

Get object list with lists from JSON with JSON.Simple


I have a JSON array with arrays inside. How can i Parse this using Json.simple.

JSON Object example:

[  
   {  
      "ID":"1",
      "Objects":[  
         {  
            "ObjectID":"5"
         },
         {  
            "ObjectID":"9"
         }
      ]
   },
   {  
      "ID":"2",
      "Objects":[  
         {  
            "ObjectID":"99"
         },
         {  
            "ObjectID":"11"
         }
      ]
   }
]

Class Foo

public int ID;
public List<Obj> Objects;

Class Obj

public int ObjectID;

so i want a list of Foo but in foo the Objects need to be filled as well

So what i need is:

List<Foo> foos = .... the output from the JSON

Solution

  • Having the following classes:

    public class Foo {
    
        private int id;
        private List<Obj> objects;
    
        // Getters and setters ommited
    }
    
    public class Obj {
    
        private int objectID;
    
        // Getters and setters ommited      
    }
    

    Use this piece of code to parse your JSON:

    String json = "[{\"ID\":\"1\",\"Objects\":[{\"ObjectID\":\"5\"},{\"ObjectID\":\"9\"}]},{\"ID\":\"2\",\"Objects\":[{\"ObjectID\":\"99\"},{\"ObjectID\":\"11\"}]}]";
    JSONParser parser = new JSONParser();
    List<Foo> foos = parseFooArray((JSONArray) parser.parse(json));
    

    That's where the magic happens:

    private List<Foo> parseFooArray(JSONArray array) {
    
        List<Foo> list = new ArrayList<>();
    
        for (Object item : array) {
            JSONObject object = (JSONObject) item;
            Foo foo = new Foo();
            foo.setId(Integer.valueOf((String) object.get("ID")));
            foo.setObjects(parseObjectArray((JSONArray) object.get("Objects")));
            list.add(foo);
        }
    
        return list;
    }
    
    private List<Obj> parseObjectArray(JSONArray array) {
    
        List<Obj> list = new ArrayList<>();
    
        for (Object item : array) {
            JSONObject object = (JSONObject) item;
            Obj obj = new Obj();
            obj.setObjectID(Integer.valueOf((String) object.get("ObjectID")));
            list.add(obj);
        }
    
        return list;
    }