我正在尝试使用我的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"}
如何为数组列表对象返回 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;
}
}
谢谢
你可以使用 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"}]
您可以重写 Site 类中的 toString 方法以返回新的 JSONObject(this).toString
你必须将数组的每个项目添加为 JSONObject 作为数组列表的索引
遍历数组列表,创建 jsonobjects,其中 Site 对象的每个元素都是 jsonobject 中的一个键、值对
然后将该 jsonObject 添加到 jsonarray 的索引中
for(int i = 0; i < allsites.length(); i++){
...
}
这是我使用 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);
输出:
[{"key 1":10,"key 2":20},{"key 1":10,"key 2":20}]