如何将String转换为Json

编程入门 行业动态 更新时间:2024-10-15 18:29:43
本文介绍了如何将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

本文发布于:2023-06-08 21:33:07,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/589445.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   如何将   String   Json

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!