Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
120 views
in Technique[技术] by (71.8m points)

java - How to convert String to Json

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 variable being something like {"name": "David"}.

How do I do this?

I have the following code but I get an error :

   Serious: Servlet.service () for servlet threw 
   exception servlet.UsuarioServlet java.lang.NullPointerException 
               at servlet.UsuarioServlet.doPost (UsuarioServlet.java: 166):

at line

String myString = new JSONObject().put("name", "Hello, World!").toString();
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...