我试图以特定顺序保存json输入,在这种情况下,我想按 id 进行排序。我该如何实现?另外,如果有人可以提供更干净的方法来进行以下过程,我们将不胜感激。
DemoConfig-POJO
服务
DemoConfig demoConfig;
JsonNode demoJson = demoConfig.getJson();
ObjectMapper mapper = new ObjectMapper();
for (JsonNode nodes : demoJson) {
JsonNode id = nodes.path("id");
JsonNode type = nodes.path("type");
JsonNode order = nodes.path("order");
JsonNode name = nodes.path("name");
JsonNode children = nodes.path("children");
ObjectNode node = mapper.createObjectNode();
node.set("id", id);
node.set("type", type);
node.set("order", order);
node.set("name", name);
node.set("children", children);
DemoConfig newDemoConfig = new DemoConfig();
newDemoConfig.setDataJson(node);
newDemoConfig.setId(id.asInt());
newDemoConfig.setType(type.asInt());
newDemoConfig.setOrder(type.asInt());
newDemoConfig.setName(name.asText());
demoRepository.save(newDemoConfig);
if(children.isArray()) {
for(JsonNode firstLevelChildren:children) {
JsonNode id1 = nodes.path("id");
JsonNode type1 = nodes.path("type");
JsonNode order1 = nodes.path("order");
JsonNode name1 = nodes.path("name");
JsonNode children1 = nodes.path("children");
ObjectNode node1 = mapper.createObjectNode();
node.set("id", id1);
node.set("type", type1);
node.set("order", order1);
node.set("name", name1);
node.set("children", children1);
DemoConfig newDemoConfig1 = new DemoConfig();
newDemoConfig1.setDataJson(node1);
newDemoConfig1.setId(id.asInt());
newDemoConfig1.setType(type.asInt());
newDemoConfig1.setOrder(type.asInt());
newDemoConfig1.setName(name.asText());
demoRepository.save(newDemoConfig1);
}
}
输入json
{
"dataJson": [
{
"id": 1,
"type": 546,
"order": 1,
"name": "demo1",
"children": []
},
{
"id": 2,
"type": 842,
"order": 2,
"name": "demo2",
"children": []
},
{
"id": 3,
"type": 985,
"order": 3,
"name": "demo4",
"children": [
{
"id": 5,
"type": 354,
"order": 4,
"name": "demo3",
"children": []
}
]
},
{
"id": 4,
"type": 810,
"order": 5,
"name": "demo5",
"children": []
}
]
}
它正在以下数据库中保存
pk_id id type order name
1000 1 546 1 demo1
1001 2 842 2 demo2
1002 3 985 3 demo3
1003 5 354 4 demo5
1004 4 810 5 demo4
无论如何,我可以根据
这样的ID进行保存pk_id id type order name
1000 1 546 1 demo1
1001 2 842 2 demo2
1002 3 985 3 demo3
1003 4 810 5 demo4
1004 5 354 4 demo5