Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
222 views
in Technique[技术] by (71.8m points)

json - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...