gpt4 book ai didi

java - ArrayList<对象> JSON

转载 作者:行者123 更新时间:2023-12-02 08:33:24 24 4
gpt4 key购买 nike

我正在尝试使用 ReSTLet 返回 JSON 数据。我可以使用以下命令返回单个项目的 JSON:

import org.json.JSONObject;

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

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

如何返回 ArrayList 对象的 JSON

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

返回:{"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"]

这是我的站点类

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相反,它可以正确处理列表的库。

<小时/>

使用示例:

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

关于java - ArrayList<对象> JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12848601/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com