如何比较JSON文档并通过Jackson或Gson返回差异?

Vel*_*aga 8 java json jackson gson

我正在使用spring-boot开发后端服务。有一种方案可以比较2个bean(一个是DB对象,另一个是客户请求的对象),然后返回“新元素”,“修改后的元素”,如果没有变化,则返回false。2豆格式如下

"sampleList":{
     "timeStamp":"Thu, 21 Jun 2018 07:57:00 +0000",
     "id":"5b19441ac9e77c000189b991",
     "sampleListTypeId":"type001",
     "friendlyName":"sample",
     "contacts":[
        {
           "id":"5b05329cc9e77c000189b950",
           "priorityOrder":1,
           "name":"sample1",
           "relation":"Friend",
           "sampleInfo":{
              "countryCode":"91",
              "numberType":"MOBILE",
              "numberRegion":"IN"
           }
        },
        {
           "id":"5b05329cc9e77c000189b950",
           "priorityOrder":1,
           "name":"sample2",
           "relation":"Friend",
           "sampleInfo":{
              "countryCode":"91",
              "numberType":"MOBILE",
              "numberRegion":"IN"
           }
        }
     ]
  }
Run Code Online (Sandbox Code Playgroud)

我已经在Java上浏览了有关此方案的bean比较的Internet,但是找不到任何更简单的解决方案,但是找到了一些很酷的JSON解决方案。我可以看到GSON的一些解决方案,但它不会返回包含“新元素”和“变更元素”的客户端对象。有什么方法可以用JSON或JAVA返回更新和修改的元素?您的帮助应该是可观的。对于我来说,即使是提示也将是一个很好的开始。

cas*_*lin 11

Maps 读取JSON文档并进行比较

您可以将两个JSON文档读为Map<K, V>。请参阅以下有关Jackson和Gson的示例:

ObjectMapper mapper = new ObjectMapper();
TypeReference<HashMap<String, Object>> type = 
    new TypeReference<HashMap<String, Object>>() {};

Map<String, Object> leftMap = mapper.readValue(leftJson, type);
Map<String, Object> rightMap = mapper.readValue(rightJson, type);
Run Code Online (Sandbox Code Playgroud)
Gson gson = new Gson();
Type type = new TypeToken<Map<String, Object>>(){}.getType();

Map<String, Object> leftMap = gson.fromJson(leftJson, type);
Map<String, Object> rightMap = gson.fromJson(rightJson, type);
Run Code Online (Sandbox Code Playgroud)

然后使用番石榴Maps.difference(Map<K, V>, Map<K, V>)来比较它们。它返回一个MapDifference<K, V>实例:

MapDifference<String, Object> difference = Maps.difference(leftMap, rightMap);
Run Code Online (Sandbox Code Playgroud)

如果您对结果不满意,可以考虑展地图,然后进行比较。它将提供更好的比较结果,尤其是对于嵌套对象和数组。

创建Flat Map进行比较

要平整地图,可以使用:

public final class FlatMapUtil {

    private FlatMapUtil() {
        throw new AssertionError("No instances for you!");
    }

    public static Map<String, Object> flatten(Map<String, Object> map) {
        return map.entrySet().stream()
                .flatMap(FlatMapUtil::flatten)
                .collect(LinkedHashMap::new, (m, e) -> m.put("/" + e.getKey(), e.getValue()), LinkedHashMap::putAll);
    }

    private static Stream<Map.Entry<String, Object>> flatten(Map.Entry<String, Object> entry) {

        if (entry == null) {
            return Stream.empty();
        }

        if (entry.getValue() instanceof Map<?, ?>) {
            return ((Map<?, ?>) entry.getValue()).entrySet().stream()
                    .flatMap(e -> flatten(new AbstractMap.SimpleEntry<>(entry.getKey() + "/" + e.getKey(), e.getValue())));
        }

        if (entry.getValue() instanceof List<?>) {
            List<?> list = (List<?>) entry.getValue();
            return IntStream.range(0, list.size())
                    .mapToObj(i -> new AbstractMap.SimpleEntry<String, Object>(entry.getKey() + "/" + i, list.get(i)))
                    .flatMap(FlatMapUtil::flatten);
        }

        return Stream.of(entry);
    }
}
Run Code Online (Sandbox Code Playgroud)

它对密钥使用RFC 6901中定义的JSON指针符号,因此您可以轻松地找到值。

考虑以下JSON文档:

{
  "name": {
    "first": "John",
    "last": "Doe"
  },
  "address": null,
  "birthday": "1980-01-01",
  "company": "Acme",
  "occupation": "Software engineer",
  "phones": [
    {
      "number": "000000000",
      "type": "home"
    },
    {
      "number": "999999999",
      "type": "mobile"
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)
{
  "name": {
    "first": "Jane",
    "last": "Doe",
    "nickname": "Jenny"
  },
  "birthday": "1990-01-01",
  "occupation": null,
  "phones": [
    {
      "number": "111111111",
      "type": "mobile"
    }
  ],
  "favorite": true,
  "groups": [
    "close-friends",
    "gym"
  ]
}
Run Code Online (Sandbox Code Playgroud)

并使用以下代码对其进行比较并显示差异:

Map<String, Object> leftFlatMap = FlatMapUtil.flatten(leftMap);
Map<String, Object> rightFlatMap = FlatMapUtil.flatten(rightMap);

MapDifference<String, Object> difference = Maps.difference(leftFlatMap, rightFlatMap);

System.out.println("Entries only on the left\n--------------------------");
difference.entriesOnlyOnLeft()
          .forEach((key, value) -> System.out.println(key + ": " + value));

System.out.println("\n\nEntries only on the right\n--------------------------");
difference.entriesOnlyOnRight()
          .forEach((key, value) -> System.out.println(key + ": " + value));

System.out.println("\n\nEntries differing\n--------------------------");
difference.entriesDiffering()
          .forEach((key, value) -> System.out.println(key + ": " + value));
Run Code Online (Sandbox Code Playgroud)

它将产生以下输出:

Entries only on the left
--------------------------
/address: null
/phones/1/number: 999999999
/phones/1/type: mobile
/company: Acme


Entries only on the right
--------------------------
/name/nickname: Jenny
/groups/0: close-friends
/groups/1: gym
/favorite: true


Entries differing
--------------------------
/birthday: (1980-01-01, 1990-01-01)
/occupation: (Software engineer, null)
/name/first: (John, Jane)
/phones/0/number: (000000000, 111111111)
/phones/0/type: (home, mobile)
Run Code Online (Sandbox Code Playgroud)

  • @cassiomolin,谢谢你的回答,写得非常清楚。第一次运行时为我工作 (2认同)

cas*_*lin 10

创建一个JSON补丁文档

除了其他答案中描述的方法之外,您还可以使用JSR 374中定义的Java API进行JSON处理(在Gson或Jackson上不使用)。需要以下依赖项:

<!-- Java API for JSON Processing (API) -->
<dependency>
    <groupId>javax.json</groupId>
    <artifactId>javax.json-api</artifactId>
    <version>1.1.2</version>
</dependency>

<!-- Java API for JSON Processing (implementation) -->
<dependency>
    <groupId>org.glassfish</groupId>
    <artifactId>javax.json</artifactId>
    <version>1.1.2</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)

然后,您可以根据JSON文档创建JSON差异。它将生成RFC 6902中定义的JSON Patch文档:

JsonPatch diff = Json.createDiff(source, target);
Run Code Online (Sandbox Code Playgroud)

当应用于源文档时,JSON补丁会生成目标文档。可以使用以下命令将JSON补丁应用于源文档:

JsonObject patched = diff.apply(source);
Run Code Online (Sandbox Code Playgroud)

创建JSON合并补丁文件

根据您的需求,您可以创建RFC 7396中定义的JSON合并补丁文件:

JsonMergePatch mergeDiff = Json.createMergeDiff(source, target);
Run Code Online (Sandbox Code Playgroud)

当应用于源文档时,JSON合并补丁程序将产生目标文档。要修补源,请使用:

JsonValue patched = mergeDiff.apply(source);
Run Code Online (Sandbox Code Playgroud)

漂亮打印JSON文档

要漂亮地打印JSON文档,可以使用:

System.out.println(format(diff.toJsonArray()));
System.out.println(format(mergeDiff.toJsonValue()));
Run Code Online (Sandbox Code Playgroud)
public static String format(JsonValue json) {
    StringWriter stringWriter = new StringWriter();
    prettyPrint(json, stringWriter);
    return stringWriter.toString();
}

public static void prettyPrint(JsonValue json, Writer writer) {
    Map<String, Object> config =
            Collections.singletonMap(JsonGenerator.PRETTY_PRINTING, true);
    JsonWriterFactory writerFactory = Json.createWriterFactory(config);
    try (JsonWriter jsonWriter = writerFactory.createWriter(writer)) {
        jsonWriter.write(json);
    }
}
Run Code Online (Sandbox Code Playgroud)

考虑以下JSON文档:

{
  "name": {
    "first": "John",
    "last": "Doe"
  },
  "address": null,
  "birthday": "1980-01-01",
  "company": "Acme",
  "occupation": "Software engineer",
  "phones": [
    {
      "number": "000000000",
      "type": "home"
    },
    {
      "number": "999999999",
      "type": "mobile"
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)
{
  "name": {
    "first": "Jane",
    "last": "Doe",
    "nickname": "Jenny"
  },
  "birthday": "1990-01-01",
  "occupation": null,
  "phones": [
    {
      "number": "111111111",
      "type": "mobile"
    }
  ],
  "favorite": true,
  "groups": [
    "close-friends",
    "gym"
  ]
}
Run Code Online (Sandbox Code Playgroud)

下面的代码生成一个JSON补丁:

JsonValue source = Json.createReader(new StringReader(leftJson)).readValue();
JsonValue target = Json.createReader(new StringReader(rightJson)).readValue();

JsonPatch diff = Json.createDiff(source.asJsonObject(), target.asJsonObject());
System.out.println(format(diff.toJsonArray()));
Run Code Online (Sandbox Code Playgroud)

它将产生以下输出:

[
    {
        "op": "replace",
        "path": "/name/first",
        "value": "Jane"
    },
    {
        "op": "add",
        "path": "/name/nickname",
        "value": "Jenny"
    },
    {
        "op": "remove",
        "path": "/address"
    },
    {
        "op": "replace",
        "path": "/birthday",
        "value": "1990-01-01"
    },
    {
        "op": "remove",
        "path": "/company"
    },
    {
        "op": "replace",
        "path": "/occupation",
        "value": null
    },
    {
        "op": "replace",
        "path": "/phones/1/number",
        "value": "111111111"
    },
    {
        "op": "remove",
        "path": "/phones/0"
    },
    {
        "op": "add",
        "path": "/favorite",
        "value": true
    },
    {
        "op": "add",
        "path": "/groups",
        "value": [
            "close-friends",
            "gym"
        ]
    }
]
Run Code Online (Sandbox Code Playgroud)

现在考虑以下代码来生成JSON合并补丁:

JsonValue source = Json.createReader(new StringReader(leftJson)).readValue();
JsonValue target = Json.createReader(new StringReader(rightJson)).readValue();

JsonMergePatch mergeDiff = Json.createMergeDiff(source, target);
System.out.println(format(mergeDiff.toJsonValue()));
Run Code Online (Sandbox Code Playgroud)

它将产生以下输出:

{
    "name": {
        "first": "Jane",
        "nickname": "Jenny"
    },
    "address": null,
    "birthday": "1990-01-01",
    "company": null,
    "occupation": null,
    "phones": [
        {
            "number": "111111111",
            "type": "mobile"
        }
    ],
    "favorite": true,
    "groups": [
        "close-friends",
        "gym"
    ]
}
Run Code Online (Sandbox Code Playgroud)

应用补丁程序时结果不同

应用补丁程序文档时,上述方法的结果略有不同。考虑以下将JSON Patch应用于文档的代码:

JsonPatch diff = ...
JsonValue patched = diff.apply(source.asJsonObject());
System.out.println(format(patched));
Run Code Online (Sandbox Code Playgroud)

它产生:

{
    "name": {
        "first": "Jane",
        "last": "Doe",
        "nickname": "Jenny"
    },
    "birthday": "1990-01-01",
    "occupation": null,
    "phones": [
        {
            "number": "111111111",
            "type": "mobile"
        }
    ],
    "favorite": true,
    "groups": [
        "close-friends",
        "gym"
    ]
}
Run Code Online (Sandbox Code Playgroud)

现在考虑以下将JSON Merge Patch应用于文档的代码:

JsonMergePatch mergeDiff = ...
JsonValue patched = mergeDiff.apply(source);
System.out.println(format(patched));
Run Code Online (Sandbox Code Playgroud)

它产生:

{
    "name": {
        "first": "Jane",
        "last": "Doe",
        "nickname": "Jenny"
    },
    "birthday": "1990-01-01",
    "phones": [
        {
            "number": "111111111",
            "type": "mobile"
        }
    ],
    "favorite": true,
    "groups": [
        "close-friends",
        "gym"
    ]
}
Run Code Online (Sandbox Code Playgroud)

在第一个示例中,occupation属性为null。在第二个示例中,将其省略。这是由于nullJSON Merge Patch 的语义所致。从RFC 7396中

如果目标确实包含该成员,则将替换该值。合并补丁中的空值具有特殊含义,以指示已删除目标中的现有值。[...]

这种设计意味着合并补丁文档适用于描述对JSON文档的修改,这些修改主要是将对象用于其结构,而不使用显式的空值。合并补丁程序格式不适用于所有JSON语法。

  • @Justin根据[RFC 8259](https://tools.ietf.org/html/rfc8259)(定义JSON格式的文档),数组元素的顺序很重要(重点是我的):_An **object** 是零个或多个名称/值对的 **无序** 集合,其中名称是字符串,值是字符串、数字、布尔值、“null”、对象或数组。**数组**是由零个或多个值组成的**有序**序列。_ 因此 `[{"f":"a"},{"f":"b"}]` 和 `[{" f":"b"},{"f":"a"}]` 是不同的。 (3认同)