0

So I'm trying to convert a dictionary into a JSON Object, the problem is that the generated JSON is not valid, the problem happens when it tries to convert the List of Maps into 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);

Here's what is generated:

    {
        "EmpId":"100-02",
        "IsSendEmployee":"Y",
        "ApprovalResponse":"",
        "EmailAnswer":"Y",
        "IsSendTC":"Y",
        "MyScheduleRecords":"[
            {
                SessionCode=371
            }, 
            {
                SessionCode=372
            }
        ]",
        "ContentType":"MS",
        "IsSendSupervisor":"N"
    }

But here's how I want it to be converted:

    [
        {
            "EmailAnswer": "Y",
            "IsSendSupervisor": "N",
            "IsSendTC": "N",
            "ContentType": "MS",
            "ApprovalResponse": "",
            "EmpId": "100-01",
            "IsSendEmployee": "Y",
            "MyScheduleRecords": [
                {
                    "SessionCode": "152"
                },
                {
                    "SessionCode": "500"
                }
            ]
        }
    ]

Does anyone know why it's not being converted correctly?

4

1 回答 1

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);
于 2013-09-10T14:35:11.200 回答