[英]Java List to json format
這是我的代碼:
public String getList() throws JSONException {
List<User> data = member.getCurrentMembers() ;
for (User u : data) {
JSONObject datas = new JSONObject();
datas.put("name", u.getUserName());
datas.put("account", u.getAccount());
datas.put("edit", u.getUserId());
datas.put("id", u.getUserId());
System.out.println(datas);
}
return str;
}
現在它將打印:
{"name":"aa","id":1,"edit":1,"account":"aa@qq.com"}
{"name":"qq","id":2,"edit":2,"account":"qq@qq.com"}
{"name":"ww","id":3,"edit":3,"account":"ww@qq.com"}
我想要的json格式是:
{
"Data": [
{"name":"aa","id":1,"edit":1,"account":"aa@qq.com"},
{"name":"qq","id":2,"edit":2,"account":"qq@qq.com"},
{"name":"ww","id":3,"edit":3,"account":"ww@qq.com"},
]
}
我能做什么?
請指導我。 謝謝
這可以解決問題
public String getList() throws JSONException {
List<User> data = member.getCurrentMembers() ;
JSONArray array = new JSONArray();
for (User u : data) {
JSONObject datas = new JSONObject();
datas.put("name", u.getUserName());
datas.put("account", u.getAccount());
datas.put("edit", u.getUserId());
datas.put("id", u.getUserId());
array.put(datas);
}
JSONObject result = new JSONObject();
result.put("Data", array);
}
希望對丹有幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.