How to convert hashmap to JSON object in Java

前端 未结 29 2037
谎友^
谎友^ 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:43

    For those using org.json.simple.JSONObject, you could convert the map to Json String and parse it to get the JSONObject.

    JSONObject object = (JSONObject) new JSONParser().parse(JSONObject.toJSONString(map));
    
    0 讨论(0)
  • 2020-11-22 11:44

    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.

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

    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"
    }
    
    0 讨论(0)
  • 2020-11-22 11:44

    I'm using Alibaba fastjson, easy and simple:

    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>VERSION_CODE</version>
    </dependency>
    

    and import:

    import com.alibaba.fastjson.JSON;
    

    Then:

    String text = JSON.toJSONString(obj); // serialize
    VO vo = JSON.parseObject("{...}", VO.class); //unserialize
    

    Everything is ok.

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

    If you need use it in the code.

    Gson gsone = new Gson();
    JsonObject res = gsone.toJsonTree(sqlParams).getAsJsonObject();
    
    0 讨论(0)
  • 2020-11-22 11:47

    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.

    0 讨论(0)
提交回复
热议问题