我编写了以下代码,以便输出ArrayList
作为JSON。当我运行代码时,我得到如下所示的输出:
{uniteids:= [{“UniteId:”:“gsheetyr”,“消息:”:“给定的用户已经是给定DL的成员。”},{“UniteId:”:“spokuri”, “消息:”:“给定用户已经是给定DL的成员。”,}}}
但是,我希望输出采用以下格式。你能告诉我我需要对我的代码做些什么改变吗?
{“uniteids”:[{“UniteId:”:“gsheetyr”,“Message:”:“给定用户已经是给定DL的成员。”},{“UniteId:”:“spokuri” ,“消息:”:“给定用户已经是给定DL的成员。”,}}}
代码:
package com.uniteid.controller;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.JSONArray;
public class JsonResponse {
public static void main(String[] args) {
List<String> retStatus = new ArrayList<String>();
Map<String, String> stat = new HashMap<String, String>();
String jsonInString = "NORESPONSE";
String jsonInString2 = "";
Map<String, String> uniteidshashMap = new HashMap<String, String>();
JSONArray ja = new JSONArray();
retStatus.add("gsheetyr: The given user is already a member of the given DL.,");
retStatus.add("spokuri : The given user is already a member of the given DL.,");
if (retStatus.size() > 0) {
for (int i = 0; i < retStatus.size(); i++) {
String splited[] = retStatus.get(i).split("\\:");
stat.put("UniteId:", splited[0]);
stat.put("Message:",splited[1]);
ja.put(stat);
System.out.println(ja);
}
jsonInString = ja.toString();
uniteidshashMap.put("uniteids:", jsonInString);
jsonInString2 = uniteidshashMap.toString();
System.out.println(jsonInString2);
}
}
}
答案 0 :(得分:0)
我相信如果您将uniteidshashMap
对象包裹在JsonArray
内并打电话给toString()
,那么您将获得更好的结果。
答案 1 :(得分:0)
试试这个
JSONArray arrayHolder = new JSONArray();
if (retStatus.size() > 0) {
for (int i = 0; i < retStatus.size(); i++) {
String splited[] = retStatus.get(i).split("\\:");
JSONObject innerObj = new JSONObject();
innerObj.put("UniteId:", splited[0]);
innerObj.put("Message:",splited[1]);
arrayHolder.put(innerObj);
}
JSONObject finalObject = new JSONObject();
finalObject.put("uniteids:", arrayHolder);
System.out.println(finalObject.toString());
}