如何在java中创建下面给出的json?

如何创建下面给出的 json?


{

    "data": [{"id":"some value", 

    "name":"some value"

    }]

}


FFIVE
浏览 102回答 2
2回答

四季花海

这取决于您的 JSON 库,但使用 org.json.simple 或 net.sf.json 会是这样的:JSONObject objectInArray = new JSONObject();objectInArray.put("id", "some value");objectInArray.put("name", "some value");JSONArray jsonArray = new JSONArray();jsonArray.add(objectInArray);JSONObject data = new JSONObject();data.put("data", jsonArray);

波斯汪

使用谷歌的 gson-2.x.jar 制作一个实体类,如public class MyEntity{&nbsp; &nbsp; @SerializedName("data")&nbsp; &nbsp; private List<Data> m_listData;&nbsp; &nbsp;//Setter getters&nbsp; &nbsp;public List<Data> getData() {&nbsp; &nbsp; &nbsp; &nbsp; return m_listData;&nbsp; &nbsp; }&nbsp; &nbsp; public void setData(List<Data> data) {&nbsp; &nbsp; &nbsp; &nbsp; this.m_listData= data;&nbsp; &nbsp; }}class Data{&nbsp; &nbsp; @SerializedName("id")&nbsp; &nbsp; private String id;&nbsp; &nbsp; @SerializedName("name")&nbsp; &nbsp; private String name;&nbsp; &nbsp; public String getId() {&nbsp; &nbsp; &nbsp; &nbsp; return id;&nbsp; &nbsp; }&nbsp; &nbsp; public void setId(String id) {&nbsp; &nbsp; &nbsp; &nbsp; this.id= id;&nbsp; &nbsp; }&nbsp; &nbsp; public String getName() {&nbsp; &nbsp; &nbsp; &nbsp; return name;&nbsp; &nbsp; }&nbsp; &nbsp; public void setName(String name) {&nbsp; &nbsp; &nbsp; &nbsp; this.name= name;&nbsp; &nbsp; }}//and then convert you json string to java objectpublic class Test{&nbsp; &nbsp; public static void main(String[] args){&nbsp; &nbsp; &nbsp; &nbsp;String jsonString="your JSON string"&nbsp; &nbsp; &nbsp; &nbsp;Gson obj_gson = new Gson();&nbsp; &nbsp; &nbsp; &nbsp;MyEntity obj_myEntity=obj_gson.fromJson(jsonString, MyEntity.class);&nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java