简体   繁体   中英

Merging Two JSONArray inside JSONObject in JAVA

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

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

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.

You must fill the lists first, and you should take out these following lines out of for loop.

        merged.get("x").addAll(xList);
        merged.get("y").addAll(yList);

BTW, it's apoor design to achieve your goal.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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