首页 > 解决方案 > 从 JSON 字符串中删除元素

问题描述

我有一个 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。但该操作无法按预期进行。

标签: javajsonstring

解决方案


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

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

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


推荐阅读