ArrayList< Object> JSON格式 [英] ArrayList<Object> JSON

查看:88
本文介绍了ArrayList< Object> JSON格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用我的restlet返回JSON数据. 我可以使用以下方式返回单个项目的JSON.

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

返回:{"name":"qwerty","url":"www.qwerty.com"}

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

如何为ArrayList对象返回JSON

How do i return JSON for ArrayList Object

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

返回:{空":false}

Returns: {"empty":false}

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

Returns: ["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 库,它可以正确处理列表.

You coud use Gson library, that handles lists properly, instead.

用法示例:

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

这篇关于ArrayList&lt; Object&gt; JSON格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆