gpt4 book ai didi

java - 在java中展平三层嵌套的JSON字符串

转载 作者:行者123 更新时间:2023-11-30 01:45:52 25 4
gpt4 key购买 nike

要求是为输入 JSON 对象创建一个通用的扁平化实用程序,将其转换为扁平化的 JSON 对象。

示例 JSON 如下所示

{
"Source": "source-1",
"Rows": [
{
"Keys": {
"device-id": "BC04-EBH-N3K-01",
"interface-name": "TenGigE0/0/0/39",
"node-name": "0/0/CPU0"
},
"Timestamp": 1567621527656,
"inner": {
"donm": {
"id": "0062",
"mol": {
"rem": 30,
"len": 11,
"org": {
"ldp": [
{
"t": 486,
"o": 322
},
{
"t": 487,
"o": 32,
"twss": 1,
"tlv": "00:01"
}
]
},
"chlen": 14,
"poe": 5,
"combs": 10,
"chaype": 4,
"rek": 0,
"rem-um": 67
},
"detail": {
"enas": "B,R",
"systes": "B,R",
"timng": 91,
"syn": "C",
"met-type": 0,
"neses": {
"lldEDIT": [
{
"ium": 830,
"m": 1,
"ass": {
"ape": "ipv4",
"ipvs": "94"
}
}
]
},
"pess": "0008",
"por]d": 0,
"pon": "BCtive",
"sysme": "BC1"
},
"reme": "Bu1",
"hean": 0,
"porl": "Et1"
}
}
}

],
"Tey": {
"epath": "Cgetail",
"sustr": "MX",
"coime": 1567621527653,
"msp": 1567621527653,
"come": 1567621527660,
"nor": "BC5",
"cid": 14789654
}
}

我一直在尝试将其扁平化为 3 个级别,并提出了以下实用程序。但是,当我必须处理数组和 String、long、Timestamp 等类型的值时,事情变得复杂。此外,我无法理解如何维护嵌套键的唯一性。

public static Map<String,Object> flattenJson(JsonNode input){
Map<String,Object> finalMap = new HashMap<>();

ObjectMapper datamapper = new ObjectMapper();
Map<String,Object> topLevelJsonMap = datamapper.convertValue(input,Map.class);
Set<String> topLevelKeys = topLevelJsonMap.keySet();

for(String topLevelKey : topLevelKeys){

System.out.println("Key :::: "+topLevelKey);

Object topLevelData = topLevelJsonMap.get(topLevelKey);
System.out.println("value :::: "+topLevelData.toString());

if(topLevelData instanceof ArrayNode){
ArrayNode arrayOfData = (ArrayNode) topLevelData;
for(JsonNode dataNode : arrayOfData){
flattenJson(input);
}
} else if(topLevelData instanceof JsonNode){
Map<String,Object> innerLevelJsonMap = datamapper.convertValue(topLevelData,Map.class);
Set<String> innerLevelKeys = innerLevelJsonMap.keySet();
for(String innerLevelKey : innerLevelKeys){
System.out.println("inner key :::: "+innerLevelKey);
flattenJson((JsonNode) innerLevelJsonMap.get(innerLevelKey));
}
}else {
finalMap.put(topLevelKey,topLevelData);
}
}
return finalMap;
}

非常感谢任何帮助。

最佳答案

您可以查看json-flattener .

顺便说一句,我是这个库的作者。

关于java - 在java中展平三层嵌套的JSON字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58008267/

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