How to convert String to Json

后端 未结 3 741
再見小時候
再見小時候 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 12:55

    Your exact problem is described by Chandra. And you may use the JSONObject using his suggestion. As you now see, its designers hadn't in mind the properties, like chaining, which made the success of other languages or libs.

    I'd suggest you use the very good Google Gson one. It makes both decoding and encoding very easy :

    The idea is that you may define your class for example as :

    public class MyClass {
       public String name = "Hello, World!";
    }
    
    private Gson gson = new GsonBuilder().create();
    PrintWriter writer = httpServletResponse.getWriter();
    writer.write( gson.toJson(yourObject));
    

提交回复
热议问题