gpt4 book ai didi

java - 动态多级层次结构 JSON 到 Java Pojo。重复用于多个项目

转载 作者:行者123 更新时间:2023-12-05 03:30:39 25 4
gpt4 key购买 nike

我有如下所示的 JSON

{
"name" : "sahal",
"address" : [
{
"state" : "FL"
},
{
"country" : "FL",
"city" : {
"type" : "municipality",
"value" : "California City"
}
},
{
"pin" : "87876"
}
]
}

键:值都不是常量。名称可以随时更改。有时名字会像 FirstName 这样出现。

我尝试使用@JsonAnySetter 和@JsonNode。这些仅适用于一个层次结构

我可以通过任何其他方式做到这一点并将其重用于其他 JSON 结构而无需编写每个项目的 Pojo ?

最佳答案

考虑使用 JsonNode 并融合层次结构循环来动态提取所有键和值,而不管模式、关系和值,

    public static void main(String[] args) throws JsonProcessingException {
//which hierarchy is your json object
JsonNode node = nodeGenerator(hierarchy);
JSONObject flat = new JSONObject();
node.fields().forEachRemaining(o -> {
if (!o.getValue().isContainerNode())
flat.put(o.getKey(), o.getValue());
else {
parser(o.getValue(), flat);
}
});
System.out.println(flat);
System.out.println(flat.get("type"));
}

public static JsonNode nodeGenerator(JSONObject input) throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
return mapper.readTree(input.toString());
}

public static void parser(JsonNode node, JSONObject flat) {
if (node.isArray()) {
ArrayNode array = node.deepCopy();
array.forEach(u ->
u.fields().forEachRemaining(o -> {
if (!o.getValue().isContainerNode())
flat.put(o.getKey(), o.getValue());
else {
parser(o.getValue(), flat);
}
}));
} else {
node.fields().forEachRemaining(o -> flat.put(o.getKey(), o.getValue()));
}
}

在您的情况下,提取的 json 将如下所示: enter image description here

关于java - 动态多级层次结构 JSON 到 Java Pojo。重复用于多个项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70781710/

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