Java中将JSON字符串拆分为多个JSON字符串

2024-02-26

我有一个类似于下面的 JSON 结构:

{
  "MyApp": "2.0",
  "info": {
    "version": "1.0.0"
  },
  "paths": {
    "MyPath1": {
      "Key": "Value"
    },
    "MyPath2": {
      "Key": "Value"
    }
  }
}

Within paths可能有可变数量的MyPath键。我想把这个结构分解成如下所示:

  • JSON 1:
{
  "MyApp": "2.0",
  "info": {
    "version": "1.0.0"
  },
  "paths": {
    "MyPath1": {
      "Key": "Value"
    }
  }
}
  • JSON 2:
{
  "MyApp": "2.0",
  "info": {
    "version": "1.0.0"
  },
  "paths": {
    "MyPath2": {
      "Key": "Value"
    }
  }
}

在 Java 中我可以选择任何简单的方法吗?


使用 Jackson(一种流行的 Java JSON 解析器),您可以获得以下内容:

String json = "{\"MyApp\":\"2.0\",\"info\":{\"version\":\"1.0.0\"},\"paths\":"
            + "{\"MyPath1\":{\"Key\":\"Value\"},\"MyPath2\":{\"Key\":\"Value\"}}}";

// Create an ObjectMapper instance the manipulate the JSON
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);

// Create a list to store the result (the list will store Jackson tree model objects)
List<JsonNode> result = new ArrayList<>();

// Read the JSON into the Jackson tree model and get the "paths" node
JsonNode tree = mapper.readTree(json);
JsonNode paths = tree.get("paths");

// Iterate over the field names under the "paths" node
Iterator<String> fieldNames = paths.fieldNames();
while (fieldNames.hasNext()) {

    // Get a child of the "paths" node
    String fieldName = fieldNames.next();
    JsonNode path = paths.get(fieldName);

    // Create a copy of the tree
    JsonNode copyOfTree = mapper.valueToTree(tree);

    // Remove all the children from the "paths" node; add a single child to "paths"
    ((ObjectNode) copyOfTree.get("paths")).removeAll().set(fieldName, path);

    // Add the modified tree to the result list
    result.add(copyOfTree);
}

// Print the result
for (JsonNode node : result) {
    System.out.println(mapper.writeValueAsString(node));
    System.out.println();
}

输出是:

{
  "MyApp" : "2.0",
  "info" : {
    "version" : "1.0.0"
  },
  "paths" : {
    "MyPath1" : {
      "Key" : "Value"
    }
  }
}

{
  "MyApp" : "2.0",
  "info" : {
    "version" : "1.0.0"
  },
  "paths" : {
    "MyPath2" : {
      "Key" : "Value"
    }
  }
}

将为每个子级创建一个新的 JSONpaths node.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Java中将JSON字符串拆分为多个JSON字符串 的相关文章

随机推荐