gpt4 book ai didi

Java - Json 数组到 json 对象

转载 作者:行者123 更新时间:2023-11-29 06:50:45 26 4
gpt4 key购买 nike

这看起来很简单,但我正在努力改变它:

{
"myList": [{
"id": 1,
"type": "EnergyBox",
"properties": ["Name : Eb1", "Prop2 : Val1", "PropN : ValN"]
}, {
"id": 2,
"type": "EnergyBox",
"properties": ["Name : Eb2", "Prop2 : Val2", "Prop3 : Val3"]
}]
}

进入这个:

{
"myList": [{
"id": 1,
"type": "EnergyBox",
"properties": {
"Name": "Eb1",
"Prop2": "Val1",
"PropN": "ValN"
}
}, {
"id": 2,
"type": "EnergyBox",
"properties": {
"Name": "Eb2",
"Prop2": "Val2",
"Prop3": "Val3"
}
}]
}

我正在使用 Java 8、Jackson 和 Simplejson 来解析数据,但不知何故,经过数小时的尝试,仍然无法正常工作。

最佳答案

我尝试根据您的要求转换 Json,请尝试以下代码。

public void test() throws JsonParseException, JsonMappingException, IOException {


String json = "{"+
"\"myList\": [{"+
"\"id\": 1,"+
"\"type\": \"EnergyBox\","+
"\"properties\": [\"Name : Eb1\", \"Prop2 : Val1\", \"PropN : ValN\"]"+
"}, {"+
"\"id\": 2,"+
"\"type\": \"EnergyBox\","+
"\"properties\": [\"Name : Eb2\", \"Prop2 : Val2\", \"Prop3 : Val3\"]"+
"}]"+
"}";

ObjectMapper mapper = new ObjectMapper();
JsonNode root = mapper.readTree(json);
JsonNode myList = root.get("myList");
myList.forEach(n -> {
System.out.println(n);
System.out.println(n.get("properties"));
ObjectNode updatedProperties = mapper.createObjectNode();
n.get("properties").forEach(p -> {
String[] vals = p.textValue().split(":");
updatedProperties.put(vals[0].trim(), vals[1].trim());
});
((ObjectNode)n).put("properties", updatedProperties);
});

System.out.println(myList);


}

关于Java - Json 数组到 json 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49067744/

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