Xear Xear - 5 months ago 15
JSON Question

How to map indexed JSON with ObjectMapper

How can I use

com.fasterxml.jackson.databind.ObjectMapper
to map a JSON like this into a list of Objects:

{
"1": {
"id": 1,
"name": "Peter Parker",
"alias": "peter"
},
"2": {
"id": 2,
"name": "Berry Allen",
"alias": "berry"
},
"3": {
"id": 3,
"name": "Tony Stark",
"alias": "tony"
}
}


I'm struggling especially with the index number. Without these consecutive numbers I would do something like the following, which is working with 'normal' object arrays very well.

ObjectMapper mapper = new ObjectMapper();
List<People> people = mapper.readValue(jsonString, new TypeReference<List<People>>(){});


I hope somebody can help me. Thanks in advance.

Answer

The JSON structure represents a map, not a list:

ObjectMapper mapper = new ObjectMapper();
Map<String, People> peopleMap = mapper.readValue(jsonString, new TypeReference<Map<String, People>>(){});
Collection<People> allPeople = peopleMap.values();
Comments