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:35

Gson can also be used to serialize arbitrarily complex objects.

Here is how you use it:

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

Gson will automatically convert collections to JSON arrays. Gson can serialize private fields and automatically ignores transient fields.

查看更多
旧人旧事旧时光
3楼-- · 2019-01-01 05:35

If you don't really need HashMap then you can do something like that:

String jsonString = new JSONObject() {{
  put("firstName", user.firstName);
  put("lastName", user.lastName);
}}.toString();

Output:

{
  "firstName": "John",
  "lastName": "Doe"
}
查看更多
春风洒进眼中
4楼-- · 2019-01-01 05:37

No need for Gson or JSON parsing libraries. Just using new JSONObject(Map<String, JSONObject>).toString(), e.g:

/**
 * convert target map to JSON string
 *
 * @param map the target map
 * @return JSON string of the map
 */
@NonNull public String toJson(@NonNull Map<String, Target> map) {
    final Map<String, JSONObject> flatMap = new HashMap<>();
    for (String key : map.keySet()) {
        try {
            flatMap.put(key, toJsonObject(map.get(key)));
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    try {
        // 2 indentSpaces for pretty printing
        return new JSONObject(flatMap).toString(2);
    } catch (JSONException e) {
        e.printStackTrace();
        return "{}";
    }
}
查看更多
琉璃瓶的回忆
5楼-- · 2019-01-01 05:37

Underscore-java library can convert hash map or array list to json and vice verse.

Code example:

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

public class Main {

    public static void main(String[] args) {

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

        System.out.println(U.toJson(map));
        // {
        //    "1": "a",
        //    "2": "b"
        // }
    }
}
查看更多
皆成旧梦
6楼-- · 2019-01-01 05:38

You can use:

new JSONObject(map);

Caution: This will only work for a Map<String, String>!

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

查看更多
路过你的时光
7楼-- · 2019-01-01 05:39

I found another way to handle it.

Map obj=new HashMap();    
obj.put("name","sonoo");    
obj.put("age",new Integer(27));    
obj.put("salary",new Double(600000));   
String jsonText = JSONValue.toJSONString(obj);  
System.out.print(jsonText);

Hope this helps.

Thanks.

查看更多
登录 后发表回答