我正在尝试使用 Restlet 返回 JSON 数据。
我可以使用以下命令返回单个项目的 JSON:
import org.json.JSONObject;
Site aSite = new Site().getSite();
JSONObject aSiteJson = new JSONObject(aSite);
return aSiteJson.toString();
返回:{"name":"qwerty","url":"www.qwerty.com"}
如何返回 ArrayList 对象的 JSON
ArrayList<Site> allSites = new SitesCollection().getAllSites();
JSONObject allSitesJson = new JSONObject(allSites);
return allSitesJson.toString();
返回:{“空”:假}
ArrayList<Site> allSites = new SitesCollection().getAllSites();
JSONArray allSitesJson = new JSONArray(allSites);
return allSitesJson.toString();
返回:[“com.sample.Site@4a7140”,“com.sample.Site@1512c2e”,“com.sample.Site@2bba21”,“com.sample.Site@c8d0b7”]
这是我的站点类
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;
}
}
Thanks
你可以使用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"}]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)