I use Jackson for converting JSON to object class.
JSON:
{ "aaa":"111", "bbb":"222", "ccc":"333" }
Object class:
class Test{ public String aaa; public String bbb;}
Code:
ObjectMapper mapper = new ObjectMapper();Object obj = mapper.readValue(content, valueType);
My code throws exception like that: org. codehaus. Jackson. Map. exc. unrecognizedpropertyexception: Unrecognized field "CCCC" (class criteria. Result. getgoodsinforesult), not marked as ignorable
And I don't want to add a prop to class test, I just want Jackson convert the exist value whith is also exist in test.
Jackson provides a few different mechanisms to configure handling of "extra" JSON elements. Following is an example of encryption ing
ObjectMapper
To notFAIL_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;}
For other approaches, see
Http://wiki.fasterxml.com/JacksonHowToIgnoreUnknown