How to convert String to Json

后端 未结 3 742
再見小時候
再見小時候 2020-12-11 12:04

I have a servlet in Java and I would like to know how I can do the following.

I have a String variable with the value of a name and want to create a Json with the v

3条回答
  •  佛祖请我去吃肉
    2020-12-11 13:04

    The json library based on Map. So, put basically returns the previous value associated with this key, which is null, so null pointer exception.( http://docs.oracle.com/javase/1.4.2/docs/api/java/util/HashMap.html#put%28java.lang.Object,%20java.lang.Object%29)

    You can rewrite the code as follows to resolve the issue.

    JSONObject jsonObject1 = new JSONObject();
    jsonObject1.put("name", "Hello, World");
    String myString = jsonObject1.toString();
    

提交回复
热议问题