【问题标题】:Remove Elements from JSON String从 JSON 字符串中删除元素
【发布时间】:2020-04-14 19:38:12
【问题描述】:

我有一个 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。但是操作并没有按预期进行。

【问题讨论】:

  • 为什么“objectJson”的内容中有转义字符\?
  • 请显示您目前使用的代码,以及您遇到的确切问题。
  • 可能是因为它是一个字符串
  • 看起来整个 JSON 格式不正确,例如 adpot 之后的引号没有转义。在这种情况下你可以使用正则表达式来切割不必要的片段\\"(userProfileOne|userProfileTwo|domainId)\\"\s*:\s*\\"(.+?)\\"\s*,?

标签: java json string


【解决方案1】:

一种可能的方法是将 json 反序列化为 java 结构,然后通过将不希望序列化的字段设置为空字段来过滤此结构。

通过使用像 Jackson 这样的框架,您可以在序列化之前在 ObjectMapper 上进行设置

mapper.setSerializationInclusion(Include.NON_NULL)。所以所有的 null 值都不会在最终的 json/result 中被序列化。

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-02-09
      • 2021-10-15
      • 2015-06-23
      • 1970-01-01
      • 1970-01-01
      • 2022-08-16
      • 2020-08-29
      相关资源
      最近更新 更多