查找JSON文件中所有JSON对象的重复键值对

jqjz2hbq  于 2022-11-19  发布在  其他
关注(0)|答案(1)|浏览(136)

我有一个JSON文件

{
    "object1": {
        "key_1": "value_1",
        "key_2": "value_2",
        "key_3": "value_3"
    },
    "object2": {
        "key_1": "value_1",
        "key_4": "value_4"
    }
}

我必须从这些JSON对象中找出重复的键值对,例如:第一个对象“object1”,我有“key_1”:“value_1”,它也出现在“object2”中,在这种情况下,我需要打印JSON文件中包含重复键值对消息。
我尝试读取每个键值对并将相同的键值对存储在HashMap中,在存储之前,我检查HashMap中是否已存在相同的键值对,一旦遇到任何重复的键值对,我将打印消息。
我的问题是,为了实现同样的事情,我们有任何开源java库吗?

xxhby3vn

xxhby3vn1#

  • Josson* 库可以转换JSON。

https://github.com/octomix/josson

// Deserialization
Josson josson = Josson.fromJsonString(
    "{" +
    "    \"object1\": {" +
    "        \"key_1\": \"value_1\"," +
    "        \"key_2\": \"value_2\"," +
    "        \"key_3\": \"value_3\"," +
    "        \"key_5\": \"value_5\"," +
    "        \"key_6\": \"value_6\"" +
    "    }," +
    "    \"object2\": {" +
    "        \"key_1\": \"value_1\"," +
    "        \"key_2\": \"value_2\"," +
    "        \"key_4\": \"value_4\"," +
    "        \"key_5\": \"value_5\"" +
    "    }" +
    "}");

// Transform    
JsonNode node = josson.getNode(
    "**.entries().map(key::value).group(obj:?).[elements.size()>1]*.obj");
System.out.println(node.toPrettyString());

输出

[ {
  "key_1" : "value_1"
}, {
  "key_2" : "value_2"
}, {
  "key_5" : "value_5"
} ]

相关问题