将值从一个JsonNode附加到另一个JsonNode字段Java

f0ofjuux  于 2023-03-06  发布在  Java
关注(0)|答案(1)|浏览(159)

我有两个JsonNode对象A和B,它们都包含一个相同的字段“segments”,我需要从JsonNode对象A中获取内容并将其附加到来自B的内容中。我需要在最终对象中同时包含来自A和B的值。
我的代码现在从A中获取了正确的内容,但是它替换了B中的所有内容。有人能帮我解决这个问题吗?最后,我需要获得一个像C这样的对象,如下所示。

public static JsonNode merge(JsonNode mainNode, JsonNode updateNode) {

        JsonNode segmentedConfigs = updateNode.get("segments");
        ((ObjectNode) mainNode).put("segments", segmentedConfigs);
        return mainNode;
    }

JSON节点A:

{
  "segments": {
    "A": {},
    "B": {},
    "C": {}
  },
  "enabled": false,
  "configStickyByClub": false,
  "sinks": {}
}

Json节点B:

{
  "segments": {
    "D": {},
    "E": {},
    "F": {}
  },
  "enabled": false,
  "configStickyByClub": false,
  "sinks": {}
}

JSON节点C:

{
  "segments": {
    "A": {},
    "B": {},
    "C": {},
    "D": {},
    "E": {},
    "F": {}
  },
  "enabled": false,
  "configStickyByClub": false,
  "sinks": {}
}
zlhcx6iw

zlhcx6iw1#

如果子节点都是ObjectNode,则需要递归合并它们:

public static void deepMerge(ObjectNode lhsNode, ObjectNode rhsNode) {
    rhsNode.fields().forEachRemaining(entry -> {
        final String key = entry.getKey();
        final JsonNode rhsChildNode = entry.getValue();
        if (rhsChildNode.isObject()) {
            final JsonNode lhsChildNode = lhsNode.get(key);
            if (lhsChildNode != null && lhsChildNode.isObject()) {
                deepMerge((ObjectNode)lhsChildNode, (ObjectNode)rhsChildNode);
            } else {
                lhsNode.put(key, rhsChildNode);
            }
        } else {
            lhsNode.put(key, rhsChildNode);
        }
    });
}

private static final String jsonA = "{\n" +
        "  \"segments\": {\n" +
        "    \"A\": {},\n" +
        "    \"B\": {},\n" +
        "    \"C\": {}\n" +
        "  },\n" +
        "  \"enabled\": false,\n" +
        "  \"configStickyByClub\": false,\n" +
        "  \"sinks\": {}\n" +
        "}";

private static final String jsonB = "{\n" +
        "  \"segments\": {\n" +
        "    \"D\": {},\n" +
        "    \"E\": {},\n" +
        "    \"F\": {}\n" +
        "  },\n" +
        "  \"enabled\": false,\n" +
        "  \"configStickyByClub\": false,\n" +
        "  \"sinks\": {}\n" +
        "}";

public static void main(String[] args) throws IOException {

    final ObjectMapper om = new ObjectMapper();

    final ObjectNode nodeA = (ObjectNode)om.readTree(new StringReader(jsonA));
    final ObjectNode nodeB = (ObjectNode)om.readTree(new StringReader(jsonB));

    deepMerge(nodeA, nodeB);

    System.out.println(nodeA.toPrettyString());
}

输出:

{
  "segments" : {
    "A" : { },
    "B" : { },
    "C" : { },
    "D" : { },
    "E" : { },
    "F" : { }
  },
  "enabled" : false,
  "configStickyByClub" : false,
  "sinks" : { }
}

相关问题