您好,我在 JSONObject 内合并 JSONArray 时遇到问题。下面是我的 JSONObject 的样子:
{
"name":"sample.bin.png",
"coords":{
"1":{"x":[ 974, 975],"y":[154, 155},
"3":{"x":[124, 125],"y":[529]},
"8":{"x":[2048, 2049],"y":[548, 560, 561, 562, 563, 564 ]}
}
}
现在我有了想要合并的 JSONObject 的键(在 coords
内)。我想分别将 x
和 y
合并到这里的一个 JSONObject 是我的代码:
String[] tokens = request().body().asFormUrlEncoded().get("coords")[0].split(","); //here i recieve the String Array Keys of the coords i want to merge
if (!image.equals("")) {
JSONObject outputJSON = getImageJSON(image); //here comes the JSON which i posted above
JSONObject coordsPack = (JSONObject) outputJSON.get("coords");
JSONObject merged = new JSONObject();
merged.put("x", new JSONArray());
merged.put("y", new JSONArray());
for (String index : tokens) {
JSONObject coordXY = (JSONObject) coordsPack.get(index);
JSONArray xList = (JSONArray) coordXY.get("x");
JSONArray yList = (JSONArray) coordXY.get("y");
merged.get("x").addAll(xList);
merged.get("y").addAll(yList);
}
System.out.println(merged);
}
但问题是我在 merged.get("x").addAll(xList);
和 merged.get("y").addAll(yList) 处遇到错误;
我无法访问这些方法。
最佳答案
您必须首先填写列表,并且应该将以下几行从 for 循环中取出。
merged.get("x").addAll(xList);
merged.get("y").addAll(yList);
顺便说一句,实现你的目标的设计很糟糕。
关于java - 在JAVA中合并两个JSONArray到JSONObject中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36981230/