ArrayList <object> JSON

I am trying to return JSON data using my restart. I can return one JSON item 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 to 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: [" [email protected] ", " [email protected] ", " [email protected] ", " [email protected] "]

Here is my class 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;
}       

}

      

thank

+1


source share


4 answers


You can use the Gson library which handles lists correctly.




Usage example:

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"}]

      

+7


source


You can override the toString method in your Site class to return a new JSONObject (this) .toString



+1


source


you need to add each element of the array as JSONObject as the index of the arraylist

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

and then add this jsonobject to the jsonarray index

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

      

0


source


here is my solution using 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);

      

Output:

[{"key 1":10,"key 2":20},{"key 1":10,"key 2":20}]

      

0


source







All Articles