gpt4 book ai didi

java - 使用 Gson 或 Jackson 将 JSON 字符串展平,使包含每个级别键值的键映射到 Map

转载 作者:行者123 更新时间:2023-12-01 13:39:23 30 4
gpt4 key购买 nike

我有一个关于 Flatten a JSON string to Map using Gson or Jackson 的增强问题.

我的场景包括重复的 key ,因此上述问题中的解决方案会导致一些重复的 key 被覆盖。所以我想通过将每个级别的键组合在一起来构造键。

那么如何实现呢?

例如:

{
"id" : "123",
"name" : "Tom",
"class" : {
"subject" : "Math",
"teacher" : "Jack"
}
}

我想得到 map :
"id" : "123",
"name" : "Tom",
"class.subject" : "Math",
"class.teacher" : "Jack"

************************更新解决方案************************ *************

基于@Manos Nikolaidis 的回答,我可以通过考虑 ArrayNode 来实现以下解决方案。
public void processJsonString(String jsonString) throws Exception {
ObjectMapper mapper = new ObjectMapper();
ArrayNode arrayNode = (ArrayNode) mapper.readTree(jsonString);
processArrayNode(arrayNode);
}

private void processObjectNode(JsonNode jsonNode) {
Map<String, String> result = new HashMap<>();
Iterator<Map.Entry<String, JsonNode>> iterator = jsonNode.fields();
iterator.forEachRemaining(node -> mapAppender(result, node, new ArrayList<String>()));
}

private void processArrayNode(ArrayNode arrayNode) {
for (JsonNode jsonNode : arrayNode) {
processObjectNode(jsonNode);
}
}


private void mapAppender(Map<String, String> result, Map.Entry<String, JsonNode> node, List<String> names) {
names.add(node.getKey());
if (node.getValue().isTextual()) {
String name = names.stream().collect(Collectors.joining("."));
result.put(name, node.getValue().asText());
} else if (node.getValue().isArray()) {
processArrayNode((ArrayNode) node.getValue());
} else if (node.getValue().isNull()) {
String name = names.stream().collect(Collectors.joining("."));
result.put(name, null);
} else {
node.getValue().fields()
.forEachRemaining(nested -> mapAppender(result, nested, new ArrayList<>(names)));
}
}

最佳答案

我使用下面的简单代码解决了这个问题,只认为需要下载 jettison 和 flattener.JsonFlattener 库

import java.util.Map;
import org.codehaus.jettison.json.JSONObject;
import com.github.wnameless.json.flattener.JsonFlattener;

public class test {

public static void main(String[] args) {
String jsonString = "{\"id\" : \"123\",\"name\" : \"Tom\",\"class\" : {\"subject\" : \"Math\",\"teacher\" : \"Jack\"}}";
JSONObject jsonObject = new JSONObject();
String flattenedJson = JsonFlattener.flatten(jsonString);
Map<String, Object> flattenedJsonMap = JsonFlattener.flattenAsMap(jsonString);
System.out.println(flattenedJsonMap);
}
}

引用链接: https://github.com/wnameless/json-flattener

关于java - 使用 Gson 或 Jackson 将 JSON 字符串展平,使包含每个级别键值的键映射到 Map<String, String>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45019130/

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