从JSON字符串中删除元素

时间:2020-04-14 19:38:12

标签: java json string

我有一个JSON字符串,如下所示:

{
   "account": "1234",
   "type": "ar-type",
   "eventTypes": "Update",
   "objectClassName": "com.triype",
   "objectJson": "{\"Name\":\"pdpot\",\"traptype\":\"adpot",\"displayName\":\"pdpot",\"experimentName\":\"pdpotpie\",\"creationTime\":\"Mar 18, 2020 5:58:58 PM\",\"createdBy\":{\"userProfileOne\":\"s:pdx\",\"userProfileTwo\":\"sid\",\"domainId\":\"did:pdx-tod-64003\"},\"lastModifiedBy\":{\"userProfileArn\":\"s:pdx-tod-64003\"},\"createdBy\":{\"userProfileOne\":\"s:p\",\"userProfileTwo\":\"si\",\"domainId\":\"did:ppot\"}}}
}

我以字符串形式获取此输入,并且在将其作为字符串传递给解析器之前,我需要执行一些字符串过滤并删除所有“ userProfileOne”,“ userProfileTwo”,“ domainId”及其键,同时又不影响JSON结构。我目前正在使用gson和json用Java编写此代码。

注意:UserProfileOne,UserProfileTwo和DomainID会多次出现。

所需的输出如下:

{
   "account": "1234",
   "type": "ar-type",
   "eventTypes": "Update",
   "objectClassName": "com.triype",
   "objectJson": "{\"Name\":\"pdpot\",\"traptype\":\"adpot",\"displayName\":\"pdpot",\"experimentName\":\"pdpotpie\",\"creationTime\":\"Mar 18, 2020 5:58:58 PM\"}}
}

当前,我正在使用substringBetween。但是该操作无法按预期进行。

2 个答案:

答案 0 :(得分:0)

我认为最好的可维护方法是创建一个与该json对应的类结构,并将其映射到该类。 在要忽略的字段上使用@JsonIgnore,然后将其从类结构映射回JSON。

另一种实现起来有点复杂的方法是遍历json中的每个节点,并在不需要时删除该节点

您也可以通过字符串匹配来做到这一点,但我认为这不是一个好方法。

答案 1 :(得分:0)

一种潜在的方法是将json反序列化为Java结构,然后通过设置为您不想序列化的null字段来过滤此结构。

通过使用类似Jackson的框架,您可以在ObjectMapper

上进行序列化之前进行设置

mapper.setSerializationInclusion(Include.NON_NULL)。因此,所有空值都不会在最终的json / result中序列化。