简体   繁体   中英

How to retain the values of each element when each element of an array is object in json in java?

I need to prepare a json file with this format: [{x: "0", y: a},{x: "1", y: b},{x: "2", y: c}]

I implemented the following technique with JSONObjects and JSONArray:

JSONArray ac=new JSONArray();
JSONObject acontent=new JSONObject();  

acontent.put("x", "0");
acontent.put("y",a);
acontent.put("x", "1");
acontent.put("y",b);
acontent.put("x", "2");
acontent.put("y",c);

ac.add(acontent);

However I could only get this output,[{x: "2", y: c}]. How can I retain all the previous values of x and y?

There are far more elegant solutions than this, but the general idea is that you need 1 object for each element in the original array.

JSONArray ac=new JSONArray();
JSONObject acontent=new JSONObject();  

acontent.put("x", "0");
acontent.put("y",a);
ac.add(acontent);
acontent = new JSONObject();

acontent.put("x", "1");
acontent.put("y",b);
ac.add(acontent);

acontent = new JSONObject();
acontent.put("x", "2");
acontent.put("y",c);

ac.add(acontent);

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