3

I have to convert a json into an object using jackson. The class is like:

class Country {  
    int a;  
    int b;  
}  

And the json i am getting:

{"country":{"a":1,"b":1}}

But when i am trying to deserialize this its giving me following error

org.codehaus.jackson.map.JsonMappingException: Unrecognized field "country"    

If i remove "country", i am able to get the object.

Is there any way i can tell jackson to just ignore "country" from the json string?

Thanks in advance.

2
  • Shall be cool to add some code sample for some one that came to you post looking for a "convert json to object using jackson" Commented Mar 24, 2011 at 1:57
  • @castanho for converting json to object you need to create an object of ObjectMapper ObjectMapper objectMapper = new ObjectMapper(); And then convert to object using readValue function A a = (A) objectMapper.readValue(jsonString, A.class) Commented Apr 26, 2011 at 6:52

1 Answer 1

4

This is the correct behavior of Jackson, the actual json representation of Country object should be without the top level country. If your json absolutely has the top level country attribute, a cleaner approach would be to use a wrapper Country class like this:

class WrapperCountry {  
   Country country;
}

this way the json representation should correctly deserialize to the WrapperCountry object and you can retrieve country from that.

Sign up to request clarification or add additional context in comments.

2 Comments

Ya i was just wondering if there's any other way to do that like an annotation. I think i will go ahead with this approach. Thanks.
You might be able to figure out what is adding that extra "country" property (and wrapper object): Jackson does not do that by default (although there is setting to get it added, in 1.7), so it is probably some other framework. Perhaps settings of the framework could be changed not to add that extra level?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.