繁体   English   中英

在JAVA中的JSONObject中合并两个JSONArray

[英]Merging Two JSONArray inside JSONObject in JAVA

嗨,我在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 )。我想将xy分别合并为一个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);

顺便说一句,要实现您的目标,这是糟糕的设计。

您是否不需要像上面两行一样先将其转换为JSONArray类?

根据@cihan 7的建议,我能够得到我的问题的答案,这是我的解决方案:

        JSONObject coordsPack = (JSONObject) outputJSON.get("coords");
        JSONObject merged = new JSONObject();
        JSONArray xList = new JSONArray();
        JSONArray yList = new JSONArray();
        for (String index : tokens) {
            JSONObject coordXY = (JSONObject) coordsPack.get(index);
            xList.addAll((JSONArray) coordXY.get("x"));
            yList.addAll((JSONArray) coordXY.get("y"));
        }
        merged.put("x", xList);
        merged.put("y", yList);
        System.out.println(merged);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM