2

I am trying to return JSON data with my restlet. I can return a single item's JSON with..

import org.json.JSONObject;

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

Returns: {"name":"qwerty","url":"www.qwerty.com"}

How do i return JSON for ArrayList Object

ArrayList<Site> allSites = new SitesCollection().getAllSites();   
JSONObject allSitesJson = new JSONObject(allSites);
return allSitesJson.toString();

Returns: {"empty":false}

ArrayList<Site> allSites = new SitesCollection().getAllSites();   
JSONArray allSitesJson = new JSONArray(allSites);
return allSitesJson.toString();

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

Here is my Site class

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


Try using colorbox http://www.jacklmoore.com/colorbox, specifically the inline html.

Set the background-color and add your buttons

4

4 に答える 4

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"}]
于 2012-10-11T21:16:21.923 に答える
1

SiteクラスのtoStringメソッドをオーバーライドして、新しいJSONObject(this).toStringを返すことができます。

于 2012-10-11T22:11:20.573 に答える
0

you have to add each item of the array as JSONObject as an index of the arraylist

loop through your arraylist, creating jsonobjects where each element of your Site object is a key,value pair in your jsonobject

and then add that jsonobject in your jsonarray's index

for(int i = 0; i < allsites.length(); i++){
    ...
}
于 2012-10-11T21:14:15.117 に答える