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.
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.
Overview. Jackson is a simple java based library to serialize java objects to JSON and vice versa.
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.
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"); }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With