2012-10-11 51 views
1

我想用我的restlet返回JSON数据。 我可以返回单个项目的JSON用..ArrayList <Object> JSON

import org.json.JSONObject; 

Site aSite = new Site().getSite(); 
JSONObject aSiteJson = new JSONObject(aSite); 
return aSiteJson.toString(); 

返回:{ “名”: “QWERTY”, “URL”: “www.qwerty.com”}

我如何返回JSON对于ArrayList对象

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(); 

返回: “[email protected]”,“com.samp [email protected]”, “[email protected]”, “[email protected]”]

这里是我的地盘类

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; 
}  

} 

感谢

回答

7

您coud使用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"}] 
+0

工程很好,Gson库需要更少的工作。谢谢 – Sprouts

+0

感谢您的解决方案。 –

0

你有到阵列的JSONObject的每个项目添加作为透过ArrayList中的数组列表

环的索引,创建一个JSONObjects您的站点对象的每个元素是在你的JSONObject的键,值对

,然后添加的JSONObject在jsonarray的指数

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

感谢您的答复。当把项目放入json数组中时... allSites.put(new JSONObject(s)); 答案是:[“{\”name \“:\”qwerty \“,\”url \“:\”www.qwerty.com \“}”,“{\”name \“:\”qwerty1 \ “\ ”URL \“:\ ”www.qwerty1.com \“}”, “{\” 名称\ “:\” qwerty2 \”,\ “URL \”:\ “www.qwerty2.com \” }“] – Sprouts

1

您可以覆盖在你的站点类的toString方法返回新的JSONObject(本)的ToString

0

这里使用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}] 
相关问题