[英]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',如果 json 对象缺少 'age' 值,
String source = "{
name : John;
age : ;
score: 100
}"
here the json might be in wrong format, I am not sure about this.这里的 json 可能格式错误,我不确定这一点。 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) com.fasterxml.jackson.databind.RuntimeJsonMappingException:[简单类型,类 org.json.JSONObject] 值的实例化失败:[某些行号] 处缺少值(通过参考链:com.bial.rs.model)
Note : JSONObject is from org.json
package注意:JSONObject 来自org.json
包
If you want to avoid NullPointerException you better make use of optString() method to extract the values from JSON如果你想避免 NullPointerException 你最好使用 optString() 方法从 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如果您随时从 JSON 中获取数据,您可能会有特定 Key 值的空数据,此时与其实现 Null 条件,不如使用这种优化方法 optString("age") 它将返回 null 并不抛出 JSONException
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.