将Map转换为JSONObject

问题描述 投票:0回答:1
import org.json.JSONArray;
import org.json.JSONObject;

    HashMap<String,String> testAttMap = new HashMap<String,String>();
        HashMap<String,String> jsonMap = new HashMap<String,String>();
        jsonMap.put("containerType", "Drive");
        testAttMap.put("idNbr", "11111111111");
        testAttMap.put("name", "ATTTT");
        jsonMap.put("testAtts", new JSONObject(testAttMap).toString());
        System.out.println(new JSONArray().put(jsonMap));   

期待:

[{"containerType":"Drive","testAtts":"{"idNbr":"11111111111","name":"ATTTT"}"}]

实际结果 :

[{"containerType":"Drive","testAtts":"{\"idNbr\":\"11111111111\",\"name\":\"ATTTT\"}"}]

有人可以建议修复吗?

java json
1个回答
1
投票

你想要做的只是:

jsonMap.put("testAtts", new JSONObject(testAttMap));

代替

jsonMap.put("testAtts", new JSONObject(testAttMap).toString());

斜线是因为你正在逃避双引号

© www.soinside.com 2019 - 2024. All rights reserved.