从Json对象中删除一个字符串

时间:2019-04-15 13:57:48

标签: java json avro

我正在尝试将Avro Kafka事件转换为Json,并且需要通过从此事件中删除字符串来操纵Avro事件。

我正在使用GSON库来操纵Json字符串对象,但是不知何故它不会删除预期的字符串。

JsonElement je = new Gson().fromJson(matchRequest, JsonElement.class);
        JsonObject jo = je.getAsJsonObject();
        jo.remove("com.XXX.XXXX");
        jo.remove("com.XXX.XXX");
        jo.remove("com.XXX.XXX");

        System.out.println("#################"+jo);

Json String I am Receiving as matchRequest is
{"interaction_id":"321","customer_id":"32","context_id":"123","work_id":"ewq","work_request_id":"213","task_type":"123","match_type":"wert","resource_list":{"com.xxx.xxxx":{"rank":1,"resource_data":{"com.xxx.xxxx":{"account_id":1,"source_name":"Mankind","channel_id":"voice"}}}},"service_list":{"com.xxx.xxxx":{"rank":5,"priority":1,"resource_count":"gvk","min_proficiency":"10","max_proficiency":"1","attributes":{"com.xxx.xxxx":{"category":"edw","value":"33232"}},"resource_offered":{"com.xxx.xxxx":{"agent_id":"rewq","account_id":"123","source_name":"wqe","resource_address":"ewq","source_address":"rewq","channel_id":"212","channel_provider":"wqe"}}}},"matching_state":"OFFERED"}

JSON格式

    "interaction_id": "321",
  "customer_id": "32",
  "context_id": "123",
  "work_id": "ewq",
  "work_request_id": "213",
  "task_type": "123",
  "match_type": "wert",
  "resource_list": {
    "com.XXXXXX": {
      "rank": 1,
      "resource_data": {
        "com.XXXX": {
          "account_id": 1,
          "source_name": "Mankind",
          "channel_id": "voice"
        }
      }
    }
  },
  "service_list": {
    "com.XXXX": {
      "rank": 5,
      "priority": 1,
      "resource_count": "gvk",
      "min_proficiency": "10",
      "max_proficiency": "1",
      "attributes": {
        "com.XXXX": {
          "category": "edw",
          "value": "33232"
        }
      },
      "resource_offered": {
        "com.XXXX": {
          "agent_id": "rewq",
          "account_id": "123",
          "source_name": "wqe",
          "resource_address": "ewq",
          "source_address": "rewq",
          "channel_id": "212",
          "channel_provider": "wqe"
        }
      }
    }
  },
  "matching_state": "OFFERED"
}

2 个答案:

答案 0 :(得分:0)

当您查看remove()方法的文档时,它需要来自 JSON 对象的参数中的键。

但是,您收到的 JSON 并不包含“ com.xxx.xxxx ”作为密钥,而是包含某些密钥,例如“ resource_list ”链接到另一个包含“ com.xxx.xxxx ”作为键的 JSON 对象。

您可能希望递归地查看收到的 JSON 对象,以删除预期的 String

答案 1 :(得分:0)

您需要对阵列执行操作:

jo.getAsJsonObject("resource_list").remove("com.XXX.XXXX");

这应该可以解决问题。