ArrayList <Object> JSON

Spr*_*uts 2 java json restlet

我试图用我的restlet返回JSON数据.我可以返回单个项目的JSON ...

import org.json.JSONObject;

Site aSite = new Site().getSite();   
JSONObject aSiteJson = new JSONObject(aSite);
return aSiteJson.toString();
Run Code Online (Sandbox Code Playgroud)

返回:{"name":"qwerty","url":"www.qwerty.com"}

我如何为ArrayList对象返回JSON

ArrayList<Site> allSites = new SitesCollection().getAllSites();   
JSONObject allSitesJson = new JSONObject(allSites);
return allSitesJson.toString();
Run Code Online (Sandbox Code Playgroud)

返回:{"empty":false}

ArrayList<Site> allSites = new SitesCollection().getAllSites();   
JSONArray allSitesJson = new JSONArray(allSites);
return allSitesJson.toString();
Run Code Online (Sandbox Code Playgroud)

返回:["com.sample.Site@4a7140","com.sample.Site @ 1512c2e","com.sample.Site@2bba21","com.sample.Site@c8d0b7"]

这是我的Site类

public class Site {
private String name;
private String url;

public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public String getUrl() {
    return url;
}
public void setUrl(String url) {
    this.url = url;
}

public Site(String name, String url) {
    super();
    this.name = name;
    this.url = url;
}       

}
Run Code Online (Sandbox Code Playgroud)

谢谢

Tim*_*kov 8

您可以使用Gson库来代替正确处理列表.


用法示例:

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"}]
Run Code Online (Sandbox Code Playgroud)