如何将String转换为Json [英] How to convert String to Json

查看:1901
本文介绍了如何将String转换为Json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆