使用jackson将json转换为对象 [英] convert json to object using jackson

查看:1195
本文介绍了使用jackson将json转换为对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须使用jackson将json转换为对象。该类如下:

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

class Country {  
    int a;  
    int b;  
}  

我得到的json:

{"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"    

如果我删除country ,我能够得到这个对象。

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

有什么办法可以让杰克逊从json字符串中忽略country吗?

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

提前致谢。

推荐答案

这是杰克逊的正确行为,实际的json表示形式国家/地区对象应该没有顶级国家/地区。如果您的json绝对具有顶级国家/地区属性,则更简洁的方法是使用这样的包装器Country类:

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;
}

这样json表示应该正确反序列化为WrapperCountry对象,你可以检索国家。

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

这篇关于使用jackson将json转换为对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆