如何在Java中转换或转换哈希图到JSON对象,并再次将JSON对象转换为JSON字符串?


当前回答

您只需枚举映射并将键-值对添加到JSONObject

方法:

private JSONObject getJsonFromMap(Map<String, Object> map) throws JSONException {
    JSONObject jsonData = new JSONObject();
    for (String key : map.keySet()) {
        Object value = map.get(key);
        if (value instanceof Map<?, ?>) {
            value = getJsonFromMap((Map<String, Object>) value);
        }
        jsonData.put(key, value);
    }
    return jsonData;
}

其他回答

首先将所有对象转换为有效的string

HashMap<String, String> params = new HashMap<>();
params.put("arg1", "<b>some text</b>");
params.put("arg2", someObject.toString());

然后将整个映射插入到org.json.JSONObject中

JSONObject postData = new JSONObject(params);

现在您可以通过调用对象的toString来获取JSON

postData.toString()
//{"arg1":"<b>some text<\/b>" "arg2":"object output"}

创建一个新的JSONObject

JSONObject o = new JSONObject(postData.toString());

或者作为通过HTTP发送的字节数组

postData.toString().getBytes("UTF-8");

如果你正在使用net.sf.json.JSONObject,那么你不会在其中找到JSONObject(map)构造函数。您必须使用公共静态JSONObject fromObject(对象对象)方法。该方法接受JSON格式的字符串、map、dynabean和javabean。

JSONObject jsonObject = JSONObject.fromObject(myMap);

这个解决方案适用于复杂的json:

public Object toJSON(Object object) throws JSONException {
    if (object instanceof HashMap) {
        JSONObject json = new JSONObject();
        HashMap map = (HashMap) object;
        for (Object key : map.keySet()) {
            json.put(key.toString(), toJSON(map.get(key)));
        }
        return json;
    } else if (object instanceof Iterable) {
        JSONArray json = new JSONArray();
        for (Object value : ((Iterable) object)) {
            json.put(toJSON(value));
        }
        return json;
    }
    else {
        return object;
    }
}

使用json的示例

Map<String, Object> data = new HashMap<String, Object>();
    data.put( "name", "Mars" );
    data.put( "age", 32 );
    data.put( "city", "NY" );
    JSONObject json = new JSONObject();
    json.putAll( data );
    System.out.printf( "JSON: %s", json.toString(2) );

输出:

JSON: {
  "age": 32,
  "name": "Mars",
  "city": "NY"
}

你也可以尝试使用谷歌的GSON。谷歌的GSON是将Java对象转换为JSON表示形式的最佳库。

http://code.google.com/p/google-gson/

就我而言,我不想要任何依赖。使用Java 8,你可以得到一个JSON字符串,如下所示:

Map<String, Object> map = new HashMap<>();
map.put("key", "value");
map.put("key2", "value2");
String json = "{"+map.entrySet().stream()
    .map(e -> "\""+ e.getKey() + "\":\"" + String.valueOf(e.getValue()) + "\"")
    .collect(Collectors.joining(", "))+"}";