How to parse following kind of JSON Array using Jackson with preserving order of the content:
{
"1": {
"title": "ABC",
"category": "Video",
},
"2": {
"title": "DEF",
"category": "Audio",
},
"3": {
"title": "XYZ",
"category": "Text",
}
}
One simple solution: rather than deserializing it directly as an array/list, deserialize it to a
SortedMap<Integer, Value>
and then just callvalues()
on that to get the values in order. A bit messy, since it exposes details of the JSON handling in your model object, but this is the least work to implement.But if you want to just have a
Collection<Value>
in your model, and hide this detail away, you can create a custom deserializer to do that. Note that you need to implement "contextualisation" for the deserializer: it will need to be aware of what the type of the objects in your collection are. (Although you could hardcode this if you only have one case of it, I guess, but where's the fun in that?)(note definitions of
hashCode()
,equals(x)
etc. are all omitted for readability)And finally here comes the deserializer implementation:
This covers at least this simple case: things like the contents of the collection being polymorphic types may require more handling: see the source of Jackson's own CollectionDeserializer.
Also, you could use UntypedObjectDeserializer as a default instead of choking if no context is given.
Finally, if you want the deserializer to return a List with the indices preserved, you can modify the above and just insert a bit of post-processing of the TreeMap: