我有一个Java的servlet,我想知道如何做到以下几点。
I have a servlet in Java and I would like to know how I can do the following.
我有一个带有名称值的String变量,想要创建一个Json,其变量类似于 {name:大卫} 。
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"}.
我该怎么做?
我有以下代码,但收到错误:
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();推荐答案
您的确切问题由Chandra描述。 你可以使用他的建议使用JSONObject。 正如你现在所看到的那样,它的设计师并没有想到链接等属性,这些属性使得其他语言或库的成功。
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.
我是建议您使用非常好的 Google Gson 。它使解码和编码变得非常简单:
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));更多推荐
如何将String转换为Json
发布评论