java - 从 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。但该操作无法按预期进行。
解决方案
我认为最好的可维护方式是创建一个与该 json 对应的类结构并将其映射到该类。在要忽略的字段上使用@JsonIgnore,然后将其从类结构映射回 JSON。
另一种实现起来有点复杂的方法是遍历 json 中的每个节点并在不需要时删除该节点
您也可以通过字符串匹配来做到这一点,但我认为这不是一个好方法。
推荐阅读
- sql - 如何从 Tableau 中的筛选器中排除值?
- symfony - Symfony 断言回调在管理类中不起作用
- python - 有没有办法在 python 中输入小写字母?
- python - 你如何区分python中的进程和线程?
- javascript - 如何编辑我的幻灯片以使其具有响应性?
- powerapps - PowerApps“无日期时间”控制小时偏移
- html - 如何在 Markdown 中编码并正确转换为 HTML?
- node.js - max-age、min-fresh 和 max-stale HTTP 标头如何从使用 Express js 作为服务器的客户端(请求标头)工作?
- python-3.x - FileNotFoundError:[Errno 2] 没有这样的文件或目录:'/Users/x/anaconda3/lib/python3.6/site-packages/numpy-1.19.4.dist-info/RECORD'
- python - 如何识别评论文本的情绪与评分不匹配的评论