如何在 Java 中将 hashmap 转换为 JSON 对象

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

stack overflow How to convert hashmap to JSON object in Java
原文答案
author avatar

接受的答案

You can use:

new JSONObject(map);

Other functions you can get from its documentation
http://stleary.github.io/JSON-java/index.html


答案:

作者头像

Gson 也可以用来序列化任意复杂的对象。

以下是你如何使用它:

Gson gson = new Gson(); 
String json = gson.toJson(myObject); 

Gson 将自动将集合转换为 JSON 数组。 Gson 可以序列化私有字段并自动忽略瞬态字段。

作者头像

You can convert Map to JSON using Jackson as follows:

Map<String,Object> map = new HashMap<>();
//You can convert any Object.
String[] value1 = new String[] { "value11", "value12", "value13" };
String[] value2 = new String[] { "value21", "value22", "value23" };
map.put("key1", value1);
map.put("key2", value2);
map.put("key3","string1");
map.put("key4","string2");

String json = new ObjectMapper().writeValueAsString(map);
System.out.println(json);

Maven Dependencies for Jackson :

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.5.3</version>
    <scope>compile</scope>
</dependency>

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.5.3</version>
    <scope>compile</scope>
</dependency>

If you are using `JSONObject` library, you can convert map to `JSON` as follows:

JSONObject Library: import org.json.JSONObject;

Map<String, Object> map = new HashMap<>();
// Convert a map having list of values.
String[] value1 = new String[] { "value11", "value12", "value13" };
String[] value2 = new String[] { "value21", "value22", "value23" };
map.put("key1", value1);
map.put("key2", value2);

JSONObject json = new JSONObject(map);
System.out.println(json);

Maven Dependencies for `JSONObject` :

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20140107</version>
</dependency>

Hope this will help. Happy coding.

作者头像

使用 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"
}

您也可以尝试使用 Google 的 GSON。Google 的 GSON 是可用于将 Java 对象转换为其 JSON 表示形式的最佳库。

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

作者头像

In my case I didn't want any dependancies. Using Java 8 you can get JSON as a string this simple:

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(", "))+"}";
作者头像

You can just enumerate the map and add the key-value pairs to the JSONObject

Method :

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;
}
作者头像

Underscore-java 库可以将哈希地图或数组列表转换为JSON和VICE诗。

import com.github.underscore.U;
import java.util.*;

public class Main {

    public static void main(String[] args) {

        Map<String, Object> map = new LinkedHashMap<>();
        map.put("1", "a");
        map.put("2", "b");

        System.out.println(U.toJson(map));
        // {
        //    "1": "a",
        //    "2": "b"
        // }
    }
}
作者头像

Better be late than never. I used GSON to convert list of HashMap to string if in case you want to have a serialized list.

List<HashMap<String, String>> list = new ArrayList<>();
HashMap<String,String> hashMap = new HashMap<>();
hashMap.add("key", "value");
hashMap.add("key", "value");
hashMap.add("key", "value");
list.add(hashMap);

String json = new Gson().toJson(list);

This json produces [{"key":"value","key":"value","key":"value"}]

作者头像

This is typically the work of a Json library, you should not try to do it yourself. All json libraries should implement what you are asking for, and you can find a list of Java Json libraries on json.org, at the bottom of the page.

作者头像

聚会迟到了,但这是我的 GSON 用于序列化 hashmap 的临时作家。我必须将键值对映射写为 json 字符串属性,期望一个特定的整数类型。我不想为这个简单的用例创建自定义 JavaBean 包装器。

GSON JsonWriter 类是易于使用的序列化程序类,包含几个强类型 writer.value() 函数。

// write Map as JSON document to http servlet response
Map<String,String> sd = DAO.getSD(123);
res.setContentType("application/json; charset=UTF-8");
res.setCharacterEncoding("UTF-8");
JsonWriter writer = new JsonWriter(new OutputStreamWriter(res.getOutputStream(), "UTF-8"));
writer.beginObject();
for(String key : sd.keySet()) {
    String val = sd.get(key);
    writer.name(key);
    if (key.equals("UniqueID") && val!=null)
        writer.value(Long.parseLong(val));
    else
        writer.value(val);
}
writer.endObject();
writer.close();

如果不需要任何自定义类型,我可以只使用 toJson() 函数。 gson-2.2.4.jar 库不到 190KB,没有任何残酷的依赖。易于在任何自定义 servlet 应用程序或独立应用程序上使用,无需大型框架集成。

Gson gson = new Gson(); 
String json = gson.toJson(myMap);