我看到了一些类似的帖子,如果这个问题已经被问过了,请提前谅解。然而,我无法使任何解决方案对我起作用。
我从一个Web服务中获取了一段JSON数据,然后我想将其存储在Amazon的DynamoDB中。但是,返回的JSON中有一些null和空值,这是DynamoDB不喜欢的。
因此,我需要从JSON中删除这些值。我目前使用Jackson进行JSON反序列化,通过readTree()方法实现,如下所示:
String sitesDataJson = webService.getData();
// create the object mapper and instruct it to skip null values
ObjectMapper mapper = new ObjectMapper();
mapper = mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
JsonNode jsonObj = null;
try {
jsonObj = mapper.readTree(sitesDataJson);
} catch (IOException e) {
e.printStackTrace();
}
我正在尝试阅读的JSON如下所示:
{
"domain_override":"",
"id":"106949",
"category_override":null,
"content_topic":null,
"modified_date":"2013-12-04 20:31:50",
"market":{
"brand_labels":{
"op":"allow_all"
},
"domains":null,
"blocked_contentattributes":{
"6":true
},
"blocked_creativetypes":{
"11":true,
"10":true,
"5":true
},
"brands":{
"ids":{
"5953":true,
"4644":true,
"8418":true,
"25480":true,
"95":true,
"5650":true
},
"op":"block"
},
"blocked_languages":{
},
"allow_unbranded_buyers":"0"
},
"type":"site",
"status":"Active",
"account_id":"100766",
"deleted":"0",
"v":"2",
"delivery_medium":"WEB",
"delivery_medium_id":"2",
"content_type_id":null,
"notes":null,
"platform_id":null,
"autorefresh_settings":{
},
"created_date":"2013-10-16 16:49:48",
"external_id":null,
}
使用NON_EMPTY或NON_NULL设置执行readTree()似乎没有任何区别。使用.toString()打印jsonObj会显示空值和null值仍然存在。
那么我是不是用错了方法?有更好(或正确的)方法吗?
我还应该补充一点,我尝试使用GSON做同样的事情,据我所知,它默认情况下会删除这些属性。但是它也没有将它们删除。这是否指向正在使用的JSON的某些奇怪之处?
但是我看不出来它可能是什么,因为我已经尝试使用非常简单的JSON测试我的代码(Jackson和GSON都试过)。
String json = "{"
+ "\"name\" : \"val1\","
+ "\"address\" : null"
+ "}";
但是当使用readTree()方法时,仍然无法删除address属性。这是否意味着NON_NULL和NON_EMPTY设置对readTree()方法没有影响?它们只用于将对象序列化为JSON吗?我是否真的需要将我的JSON读入POJO以处理null或空值?
非常感谢。
null
值是可以的,但空字符串(或数组)不行。@AnindaBhattacharyya 给出的解决方案对我很有用。 - tuscland