所以我试图将字典转换为JSON对象,问题是生成的JSON无效,当它尝试将地图列表转换为JSON时会发生问题
final List<Map<String,Object>> sessions = new ArrayList<Map<String,Object>>();
Map<String,Object> sessionDict = null;
for (String session : SessionsList) {
sessionDict = new HashMap<String,Object>();
sessionDict.put("SessionCode", session);
sessions.add(sessionDict);
}
Map<String,Object> map = new HashMap<String,Object>(){
private static final long serialVersionUID = 1L;
{
put("EmailAnswer", "Y");
put("IsSendSupervisor", isSendSup);
put("IsSendTC", isSendTC);
put("ContentType", "MS");
put("ApprovalResponse", "");
put("EmpId", empId);
put("IsSendEmployee", isSendEmp);
put("MyScheduleRecords", sessions);
}};
JSONObject json = new JSONObject(map);
以下是生成的内容:
{
"EmpId":"100-02",
"IsSendEmployee":"Y",
"ApprovalResponse":"",
"EmailAnswer":"Y",
"IsSendTC":"Y",
"MyScheduleRecords":"[
{
SessionCode=371
},
{
SessionCode=372
}
]",
"ContentType":"MS",
"IsSendSupervisor":"N"
}
但是我希望如何转换它:
[
{
"EmailAnswer": "Y",
"IsSendSupervisor": "N",
"IsSendTC": "N",
"ContentType": "MS",
"ApprovalResponse": "",
"EmpId": "100-01",
"IsSendEmployee": "Y",
"MyScheduleRecords": [
{
"SessionCode": "152"
},
{
"SessionCode": "500"
}
]
}
]
有谁知道为什么没有正确转换?
答案 0 :(得分:1)
试试这段代码 -
Map<String,Object> map = new HashMap<String,Object>(){
private static final long serialVersionUID = 1L;
{
put("EmailAnswer", "Y");
put("IsSendSupervisor", isSendSup);
put("IsSendTC", isSendTC);
put("ContentType", "MS");
put("ApprovalResponse", "");
put("EmpId", empId);
put("IsSendEmployee", isSendEmp);
}};
编辑 -
JSONArray jsonArray = new JsonArray();
for (String session : SessionsList) {
JsonObject jsonObject2 = new JSONObject();
jsonObject2.put("SessionCode", session);
jsonArray.add(jsonObject2)
}
JSONObject json = new JSONObject(map);
json.put("MyScheduleRecords", jsonArray);