I am having a question with Jackson that I think should be simple to solve, but it is killing me.
Let's say I have a java POJO class that looks like this (assume Getters and Setters for me):
class User { private String name; private Integer age; }
And I want to deserialize JSON that looks like this into a User object:
{ "user": { "name":"Sam Smith", "age":1 } }
Jackson is giving me issues because the User is not the first-level object in the JSON. I could obviously make a UserWrapper class that has a single User object and then deserialize using that but I know there must be a more elegant solution.
How should I do this?
How to ignore parent tag from json?? String str = "{\"parent\": {\"a\":{\"id\": 10, \"name\":\"Foo\"}}}"; And here is the class to be mapped from json. (a) Annotate you class as below @JsonRootName(value = "parent") public class RootWrapper { (b) It will only work if and only if ObjectMapper is asked to wrap.
According to the modified Backus-Naur-Form on the right side pane of http://json.org/ the root element of a JSON data structure can be any of these seven types/values: Object Array String Number true false null.
@JsonRootName allows to have a root node specified over the JSON. We need to enable wrap root value as well.
The @JsonProperty annotation is used to map property names with JSON keys during serialization and deserialization. By default, if you try to serialize a POJO, the generated JSON will have keys mapped to the fields of the POJO.
edit: this solution only works for jackson < 2.0
For your case there is a simple solution:
@JsonRootName(value = "user")
;om.configure(Feature.UNWRAP_ROOT_VALUE, true);
(as for 1.9) and om.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
(for version 2).That's it!
@JsonRootName(value = "user") public static class User { private String name; private Integer age; public String getName() { return name; } public void setName(final String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(final Integer age) { this.age = age; } @Override public String toString() { return "User [name=" + name + ", age=" + age + "]"; } } ObjectMapper om = new ObjectMapper(); om.configure(Feature.UNWRAP_ROOT_VALUE, true); System.out.println(om.readValue("{ \"user\": { \"name\":\"Sam Smith\", \"age\":1 }}", User.class));
this will print:
User [name=Sam Smith, age=1]
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