简体   繁体   中英

How to add object for each element in a single array in JSON using java?

I need to create an array with multiple objects in json. The output is supposed to be like this:

[{x: "0-9", y: 20},{x: "10-19", y: 30},{x: "20-29", y: 30}]

What would be the best way to do this?

I used the following method which doesnt seem to fit for large number of arrays

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

acontent.put("x", "10-19");

acontent.put("y",30);

You can create a proper model:

public class MyPair {
    private String x;
    private int y;
    // + getters and setters
}

public static writeJson() {
    List<MyPair> mps = createMyPairList();
    // write mps as JSON
}

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