在 JAVA 中合并 JSONObject 中的两个 JSONArray [英] Merging Two JSONArray inside JSONObject in JAVA

查看:69
本文介绍了在 JAVA 中合并 JSONObject 中的两个 JSONArray的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 JSONObject 中合并 JSONArray 时遇到问题.下面是我的 JSONObject 的样子:

Hi i have a problem regarding the merge of JSONArray inside JSONObject. Below is what my JSONObject looks like:

{
 "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 ]}
          }
 }

现在我有我想要合并的那些 JSONObjects 的键(在 coords 内).我想分别将 xy 合并到这里的一个 JSONObject 是我的代码:

Now i have keys of those JSONObjects which i want to merge (inside coords).I wanted to merge x and y respectively into one JSONObject here is my code:

     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) 有错误; 我无法访问这些方法.

but problem is that i am having error at merged.get("x").addAll(xList); and merged.get("y").addAll(yList); i am unable to access the methods.

推荐答案

根据@cihan 七的建议,我可以得到我的问题的答案,这是我的解决方案:

As per suggestion of @cihan seven i am able to get the answer of my problem here is my solution:

        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);

这篇关于在 JAVA 中合并 JSONObject 中的两个 JSONArray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆