How to convert hashmap to JSON object in Java

前端 未结 29 2003
谎友^
谎友^ 2020-11-22 11:20

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

相关标签:
29条回答
  • 2020-11-22 11:32

    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(", "))+"}";
    
    0 讨论(0)
  • 2020-11-22 11:32
        import org.json.JSONObject;
    
        HashMap<Object, Object> map = new HashMap<>();
        String[] list={"Grader","Participant"};
        String[] list1={"Assistant","intern"};
        map.put("TeachingAssistant",list);
        map.put("Writer",list1);
        JSONObject jsonObject = new JSONObject(map);
        System.out.printf(jsonObject.toString());
    
        // Result: {"TeachingAssistant":["Grader","Participant"],"Writer":["Assistant","intern"]}
    
    0 讨论(0)
  • 2020-11-22 11:33

    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.

    0 讨论(0)
  • 2020-11-22 11:34

    this works for me :

    import groovy.json.JsonBuilder
    properties = new Properties()
    properties.put("name", "zhangsan")
    
    println new JsonBuilder(properties).toPrettyString()
    
    0 讨论(0)
  • 2020-11-22 11:35

    If you are using net.sf.json.JSONObject then you won't find a JSONObject(map) constructor in it. You have to use the public static JSONObject fromObject( Object object ) method. This method accepts JSON formatted strings, Maps, DynaBeans and JavaBeans.

    JSONObject jsonObject = JSONObject.fromObject(myMap);

    0 讨论(0)
  • 2020-11-22 11:36

    Late to the party but here is my GSON adhoc writer for serializing hashmap. I had to write map of key-value pairs as json string attributes, expect one specific to be integer type. I did not want to create custom JavaBean wrapper for this simple usecase.

    GSON JsonWriter class is easy to use serializer class containing few strongly typed writer.value() functions.

    // 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();
    

    If none of the custom types be needed I could have just use toJson() function. gson-2.2.4.jar library is just under 190KB without any brutal dependencies. Easy to use on any custom servlet app or standalone application without big framework integrations.

    Gson gson = new Gson(); 
    String json = gson.toJson(myMap); 
    
    0 讨论(0)
提交回复
热议问题