简体   繁体   中英

Ignore missing values of key during jackson json deserialize to JSONObject class in java

In the example

If the json object has a missing value for 'age',

 String source = "{
    name : John;
    age : ;
    score: 100
 }"

here the json might be in wrong format, I am not sure about this. And I want to ignore those keys which don't have values.

JSONObject object = objectMapper.readValue(source, JSONObject.class);

Error getting:

com.fasterxml.jackson.databind.RuntimeJsonMappingException: Instantiation of [simple type, class org.json.JSONObject] value failed: Missing value at [some line number] (through reference chain: com.bial.rs.model)

Note : JSONObject is from org.json package

If you want to avoid NullPointerException you better make use of optString() method to extract the values from JSON

If you are fetching the data from JSON at any time, you might have null data for a particular Key value, at that time instead of implementing Null conditions, better make use of this optimized method optString("age") it will return null and does not throw JSONException

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM