Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson JSON : top level segment inclusion

Tags:

json

jackson

I am referring to this post: convert json to object using jackson , and the last answer there by StaxMan, which says it's possible in Jackson 1.7 to set the configuration such that Jackson starts producing (and maybe parsing too?) the top-level tag/segment in the JSON.

Can someone shed some light on how to set that configuration, and it is only for JSON generation or parsing as well?

Thank you very much!

like image 935
Anand Avatar asked Oct 12 '22 06:10

Anand


1 Answers

You need to create and configure the ObjectMapper with the WRAP_ROOT_VALUE feature, e.g.

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(SerializationConfig.Feature.WRAP_ROOT_VALUE, true);

See javadoc:

Feature that can be enabled to make root value (usually JSON Object but can be any type) wrapped within a single property JSON object, where key as the "root name", as determined by annotation introspector (esp. for JAXB that uses @XmlRootElement.name) or fallback (non-qualified class name). Feature is mostly intended for JAXB compatibility.

Default setting is false, meaning root value is not wrapped.

The javadoc also says that it hasn't yet been implemented, but I can see it being used in the Jackson source, so it might work OK. I haven't actually tried it myself, though.

like image 97
skaffman Avatar answered Oct 14 '22 23:10

skaffman