简体   繁体   English

在 jackson json 反序列化为 Java 中的 JSONObject 类期间忽略键的缺失值

[英]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.

相关问题 在 Java Jackson JSON 反序列化过程中忽略丢失的属性 - Ignore missing properties during Jackson JSON deserialization in Java Java / Jackson:使用HashMap将JSON反序列化为类 - Java/Jackson: Deserialize JSON into class with HashMap jackson:将 json 反序列化为 java 映射,忽略一些条目 - jackson: deserialize json to java map, ignore some entries 杰克逊反序列化缺少的默认值 - Jackson deserialize default values missing 如何使用 java 中的 jackson 将缺失的属性反序列化为默认值 - How to Deserialize missing properties to default values with jackson in java Jackson JSON:如何在 Java 中使用 setter 将 double 反序列化为类 - Jackson JSON: how to deserialize double to class using setter in java 无法在 Java 中使用 Jackson 反序列化扩展抽象类 json - Can't deserialize extended abstract class json using Jackson in Java 如果使用Jackson在java对象中存在属性(应该忽略json元素),如何将Json反序列化为java对象? - How to deserialize Json into java object if a property is not present in the java object(should ignore json element)using Jackson? 在使用Jackson进行反序列化期间有选择地忽略JSON属性 - Selectively ignoring JSON properties during deserialize with Jackson 杰克逊反序列化json字符串,但是bean缺少json字符串的属性/密钥 - Jackson deserialize json string but bean missing json string's property/key
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM