Search code examples
javajsonpojo

Create POJO from json generated by key=>value Array


I want create a pojo from a json like this

{
        "1": [
            {
                "idmapel": 1,
                "label": "Fisika"
            },
            {
                "idmapel": 2,
                "label": "Kimia"
            },
            {
                "idmapel": 3,
                "label": "Biologi"
            },
            {
                "idmapel": 4,
                "label": "Matematika"
            },
        ],
  "2":[
    {
        "idmapel": 1,
        "label": "Fisika"
    }
  ]
}

when i generate from http://www.jsonschema2pojo.org/ it created a 1 and 2 class, but imagine if i have more than 2 keys. i want to be able to access element by something like this ObjectClass::getList(1) or ObjectClass::getList(2)


Solution

  • You can use a Map to do this.

    Map<String, List<Pojo>> map = deserialize(jsonSring);
    

    where Pojo is the class which has fields idmapel and label, deserialize is a method which deserializes the json to object and jsonString is the json string value to deserialize. Then you can access lists with keys

    List<Pojo> list1 = map.get("1");
    List<Pojo> list2 = map.get("2");