On Tue, Oct 17, 2017 at 10:50 AM, Steinar Bang <[email protected]> wrote: > What's the simplest and most elegant way to serialize an array of > JSON objects into a Java map with jackson? > > I've just used the jackson deserializer by creating beans matching the > JSON objects to be deserialized. > > Ie. this > { > "id": "something", > "year": 2016, > "items": [ > { > "id": "something_else", > "amount": 123445, > "specification": "something" > } > ] > } > > Into > public class TopLevel { > private String id; > private int year; > private List<Item> items; > > // + public getters for all fields > } > and > public class Item { > private String id; > private long amount; > private String specification; > } > > When I started to use the parsed objects I quickly found out that I > would prefer TopLevel.items to be a Map<String,Item>, keyed on the > Item.id values, instead of a List<Item>. > > So I googled "serializing JSON array into map with Jackson", and got > answers... but they seemed awfully complicated compared to the existing > configuration-free parsing. > > So I rewrote the TopLevel.getItems() method to return Map<String,Item>, > added a Map<String,Item> field with lazy initialization. > > Ie. the pragmatic solution, and I can live fine with the pragmatic > solution. > > But if there is a more elegant and correct jacksonian way of > deserializing the array directly into a map I could switch to that.
There is an open issue/RFE for actually supporting something like this: https://github.com/FasterXML/jackson-databind/issues/1152 although I didn't have time to work on this for 2.9, and do not have active plans for implementing it. But the idea itself seems valid for multiple reasons, as this seems like relatively common use case. Other than that I think your best bet is to use "converting" serializer/deserializer, either by custom (de)serializer or by using @JsonDeserialize(converter = Converter.class) @JsonSerialize(converter = Converter.class) and implement Converter from intermediate type that Jackson can bind JSON to first (for deserialization), or serialize from (serialization), and your Converter takes care of converting between actual value types and that intermediate type. Intermediate type is the thing that maps 1-to-1 to/from JSON, so here either array or `List`; and actual type as declared, Map. I hope this helps, -+ Tatu +- -- You received this message because you are subscribed to the Google Groups "jackson-user" group. To unsubscribe from this group and stop receiving emails from it, send an email to [email protected]. To post to this group, send email to [email protected]. For more options, visit https://groups.google.com/d/optout.
