首页 > 解决方案 > 将 Map 转换为 JSONObject

问题描述

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\"}"}]

任何人都可以建议修复吗?

标签: javajson

解决方案


你想做的很简单:

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

代替

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

斜线在那里是因为你正在转义双引号


推荐阅读