How to convert hashmap to JSON object in Java

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

    First convert all your objects into valid Strings

    HashMap params = new HashMap<>();
    params.put("arg1", "some text");
    params.put("arg2", someObject.toString());
    

    Then insert the entire map into a org.json.JSONObject

    JSONObject postData = new JSONObject(params);
    

    Now you can get the JSON by simply calling the object's toString

    postData.toString()
    //{"arg1":"some text<\/b>" "arg2":"object output"}
    

    Create a new JSONObject

    JSONObject o = new JSONObject(postData.toString());
    

    Or as a byte array for sending over HTTP

    postData.toString().getBytes("UTF-8");
    

提交回复
热议问题