我正在尝试组合具有相同方向类型的最近 json 对象。以下是 JSON 结构
{
"section": "1",
"data": [
{
"orientation": "P",
"type": "html",
"headerContent": true,
"footerContent": true,
"pageContent": "<h3>Section : BCP Incident Response<hr><\/h3>"
},
{
"orientation": "P",
"type": "html",
"headerContent": true,
"footerContent": true,
"pageContent": "second json"
},
{
"orientation": "L",
"pageContent": "lll.pdf"
},
{
"orientation": "L",
"type": "html",
"headerContent": true,
"footerContent": true,
"pageContent": "landscape1"
},
{
"orientation": "P",
"type": "html",
"headerContent": true,
"footerContent": true,
"pageContent": "landscape2"
},
{
"orientation": "L",
"type": "html",
"headerContent": true,
"footerContent": true,
"pageContent": "last"
}
]
}
expected json output
[
{
"orientation": "P",
"type": "html",
"headerContent": true,
"footerContent": true,
"pageContent": "<h3>Section : BCP Incident Response<hr><\/h3> second json"
},
{
"orientation": "L",
"pageContent": "lll.pdf landscape1"
},
{
"orientation": "P",
"type": "html",
"headerContent": true,
"footerContent": true,
"pageContent": "landscape2"
},
{
"orientation": "L",
"type": "html",
"headerContent": true,
"footerContent": true,
"pageContent": "last"
}
]
我正在使用 switch 语句来检查方向类型 compine。但它不能正常工作。
JsonNode dataNode = root.path("data");
if (dataNode.isArray()) {
// If this node an Arrray?
System.out.println("node an Arrray");
}
StringBuilder pageContent = new StringBuilder();
StringBuilder pageContent2 = new StringBuilder();
Map<String, String> fields = new HashMap<String, String>();
ArrayList<Map<String,String>> mergeList = new ArrayList<>();
for (JsonNode node : dataNode) {
switch (node.path("orientation").asText()) {
case "P":
if(pageContent2.length()>0){
fields.put("orientation", "L");
fields.put("pageContent", pageContent2.toString());
mergeList.add(fields);
pageContent2.setLength(0);
}
pageContent.append(node.path("pageContent").asText());
break;
case "L":
if(pageContent.length()>0){
fields.put("orientation", "P");
fields.put("pageContent", pageContent.toString());
mergeList.add(fields);
pageContent.setLength(0);
}
pageContent2.append(node.path("pageContent").asText());
break;
default:
throw new IllegalArgumentException("Invalid data! ");
}
这是我的代码。我在堆栈中发现了一些合并示例,例如将两个 json 对象合并到 java 中的单个对象中没有帮助。