gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 08:33:32 25 4
gpt4 key购买 nike

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

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

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 中有什么我可以选择的简单方法吗?

最佳答案

使用流行的 Java JSON 解析器 Jackson,您可以拥有以下内容:

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"
}
}
}

将为 paths 节点的每个子节点创建一个新的 JSON。

关于java - 在 Java 中将 JSON 字符串拆分为多个 JSON 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39406517/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com