jackson无法识别的领域

我使用jackson将JSON转换为对象类。

JSON:

{ "aaa":"111", "bbb":"222", "ccc":"333" } 

对象类:

 class Test{ public String aaa; public String bbb; } 

码:

 ObjectMapper mapper = new ObjectMapper(); Object obj = mapper.readValue(content, valueType); 

我的代码抛出像这样的exception:

 org.codehaus.jackson.map.exc.UnrecognizedPropertyException: Unrecognized field "cccc" (Class com.isoftstone.banggo.net.result.GetGoodsInfoResult), not marked as ignorable 

我不想添加一个道具类testing,我只是希望jackson转换的存在值whith也存在于testing。

Jackson提供了几种不同的机制来configuration“额外”JSON元素的处理。 以下是将ObjectMapperconfiguration为不FAIL_ON_UNKNOWN_PROPERTIES

 import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility; import org.codehaus.jackson.annotate.JsonMethod; import org.codehaus.jackson.map.DeserializationConfig; import org.codehaus.jackson.map.ObjectMapper; public class JacksonFoo { public static void main(String[] args) throws Exception { // { "aaa":"111", "bbb":"222", "ccc":"333" } String jsonInput = "{ \"aaa\":\"111\", \"bbb\":\"222\", \"ccc\":\"333\" }"; ObjectMapper mapper = new ObjectMapper().setVisibility(JsonMethod.FIELD, Visibility.ANY); mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); Test test = mapper.readValue(jsonInput, Test.class); } } class Test { String aaa; String bbb; } 

有关其他方法,请参阅http://wiki.fasterxml.com/JacksonHowToIgnoreUnknown

从Jackson 2.0开始,内部枚举(DeserializationConfig.Feature)已经被移动到独立枚举(DeserializationFeature):

mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

如果您使用的是Jackson 2.0(fasterxml)

 ObjectMapper mapper = new ObjectMapper(); mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); 

事先注意可能导致业务逻辑故障的模型的关键变化是重要的。

为了更好地控制应用程序,最好手动处理这个exception。

 objectMapper.addHandler(new DeserializationProblemHandler() { @Override public boolean handleUnknownProperty(DeserializationContext ctxt, JsonParser jp, JsonDeserializer<?> deserializer, Object beanOrClass, String propertyName) throws IOException, JsonProcessingException { String unknownField = String.format("Ignoring unknown property %s while deserializing %s", propertyName, beanOrClass); Log.e(getClass().getSimpleName(), unknownField); return true; } }); 

返回true以处理UnrecognizedPropertyException

不要无视默默无闻的领域。