ArrayList<Object> JSON

橙三吉。 提交于 2019-12-01 23:02:40

You coud use Gson library, that handles lists properly, instead.


Usage example:

class BagOfPrimitives {
    private int value1;
    private String value2;
    private transient int value3;
    public BagOfPrimitives(int value1, String value2, int value3) {
        this.value1 = value1;
        this.value2 = value2;
        this.value3 = value3;
    }
}

BagOfPrimitives obj1 = new BagOfPrimitives(1, "abc", 3);
BagOfPrimitives obj2 = new BagOfPrimitives(32, "gawk", 500);
List<BagOfPrimitives> list = Arrays.asList(obj1, obj2);
Gson gson = new Gson();
String json = gson.toJson(list);  
// Now json is [{"value1":1,"value2":"abc"},{"value1":32,"value2":"gawk"}]

You could override the toString method in your Site class to return new JSONObject(this).toString

you have to add each item of the array as JSONObject as an index of the arraylist

loop through your arraylist, creating jsonobjects where each element of your Site object is a key,value pair in your jsonobject

and then add that jsonobject in your jsonarray's index

for(int i = 0; i < allsites.length(); i++){
    ...
}

here is my solution using simple-json.

JSONArray jr = new JSONArray();
for (int x = 1; x <= number_of_items; x++)
    {
        JSONObject obj = new JSONObject();
        obj.put("key 1", 10);
        obj.put("key 2", 20);
        jr.add(obj);

    }
System.out.print(jr);

Output:

[{"key 1":10,"key 2":20},{"key 1":10,"key 2":20}]
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!