How to convert hashmap to JSON object in Java

2019-01-01 04:55发布

How to convert or cast hashmap to JSON object in Java, and again convert JSON object to JSON string?

标签: java json
23条回答
唯独是你
2楼-- · 2019-01-01 05:20

You can use Gson. This library provides simple methods to convert Java objects to JSON objects and vice-versa.

Example:

GsonBuilder gb = new GsonBuilder();
Gson gson = gb.serializeNulls().create();
gson.toJson(object);

You can use a GsonBuilder when you need to set configuration options other than the default. In the above example, the conversion process will also serialize null attributes from object.

However, this approach only works for non-generic types. For generic types you need to use toJson(object, Type).

More information about Gson here.

Remember that the object must implement the Serializable interface.

查看更多
冷夜・残月
3楼-- · 2019-01-01 05:21

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(", "))+"}";
查看更多
萌妹纸的霸气范
4楼-- · 2019-01-01 05:21

If you use complex objects, you should apply enableComplexMapKeySerialization(), as stated in https://stackoverflow.com/a/24635655/2914140 and https://stackoverflow.com/a/26374888/2914140.

Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create();
Map<Point, String> original = new LinkedHashMap<Point, String>();
original.put(new Point(5, 6), "a");
original.put(new Point(8, 8), "b");
System.out.println(gson.toJson(original));

Output will be:

{
 "(5,6)": "a",
 "(8,8)": "b"
}
查看更多
冷夜・残月
5楼-- · 2019-01-01 05:22

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;
}
查看更多
泛滥B
6楼-- · 2019-01-01 05:23

If you need use it in the code.

Gson gsone = new Gson();
JsonObject res = gsone.toJsonTree(sqlParams).getAsJsonObject();
查看更多
泛滥B
7楼-- · 2019-01-01 05:24

Here my single-line solution with GSON:

myObject = new Gson().fromJson(new Gson().toJson(myHashMap), MyClass.class);
查看更多
登录 后发表回答