Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding JSON child object property into Java object field in Jackson

Tags:

I have a JSON object, say:

{   "foo": {     "bar": 1   },   "baz": 2 } 

and I want to bind it into a Java object, like:

@JsonIgnoreProperties(ignoreUnknown = true) public class Foo {   private int bar;   @JsonProperty("baz")   private int baz; } 

How can I set the value of foo.bar from JSON to the bar field in the Foo Java object?

I've tried annotating the field with @JsonProperty("foo.bar"), but it doesn't work like that.

like image 261
hleinone Avatar asked Nov 16 '10 22:11

hleinone


People also ask

How does Jackson read nested JSON?

A JsonNode is Jackson's tree model for JSON and it can read JSON into a JsonNode instance and write a JsonNode out to JSON. To read JSON into a JsonNode with Jackson by creating ObjectMapper instance and call the readValue() method. We can access a field, array or nested object using the get() method of JsonNode class.

Which methods does Jackson rely on to serialize a Java object *?

Overview. Jackson is a simple java based library to serialize java objects to JSON and vice versa.

How do I map nested values with Jackson?

Mapping With Annotations To map the nested brandName property, we first need to unpack the nested brand object to a Map and extract the name property. To map ownerName, we unpack the nested owner object to a Map and extract its name property.


2 Answers

This ain't perfect but it's the most elegant way I could figure out.

@JsonProperty("foo") public void setFoo(Map<String, Object> foo) {   bar = (Integer) foo.get("bar"); } 
like image 89
hleinone Avatar answered Oct 04 '22 08:10

hleinone


There is no automated functionality for this (as far as I know), but this is a somewhat often requested feature; there is this Jira RFE: http://jira.codehaus.org/browse/JACKSON-132 that sounds like what you are looking for.

like image 26
StaxMan Avatar answered Oct 04 '22 08:10

StaxMan