Xear Xear - 1 year ago 121
JSON Question

How to map indexed JSON with ObjectMapper

How can I use

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 Source

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