2012-10-11 131 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}] 
相關問題