java 相当于 json_encode(在 PHP 中)的 JSP 是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3207092/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 00:48:40  来源:igfitidea点击:

What is the JSP equivalent to json_encode ( in PHP )?

javaphpjsonjspservlets

提问by jeph perro

I am trying to encode a JSP servlet into JSON. What's the equivalent in JSP to json_encode() in PHP ?

我正在尝试将 JSP servlet 编码为 JSON。JSP 中的等价于 PHP 中的 json_encode() 是什么?

采纳答案by BalusC

JSP/Servlet isn't that high-level as PHP which has practically "anything built-in". In Java you've more freedom to choose from libraries. There are several JSON libraries in Java available which you can implement in your webapp, the popular ones being under each JSON.org, Hymansonand Google Gson.

JSP/Servlet 不像 PHP 那样高级,它实际上“内置了任何东西”。在 Java 中,您可以更自由地从库中进行选择。有几个可用的 Java JSON 库,您可以在您的 web 应用程序中实现它们,流行的库位于JSON.orgHymansonGoogle Gson 下

We use here Gson to our satisfaction. It has excellent support for parameterized collections and (nested) Javabeans. It's basically as simple as follows:

我们在这里使用 Gson 令我们满意。它对参数化集合和(嵌套的)Javabean 有很好的支持。它基本上很简单,如下所示:

String json = new Gson().toJson(anyObject); // anyObject = List<Bean>, Map<K, Bean>, Bean, String, etc..
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);

Converting JSON to a fullworthy Javabean is also simple with Gson, see this example.

使用 Gson 将 JSON 转换为完整的 Javabean 也很简单,请参阅此示例

回答by Henry

Gson is pretty cool.

Gson 很酷。

Its almost the same as json_encode. Note that an encoded empty string in json_encodeevaluates to "\"\""

它几乎与json_encode. 请注意,编码的空字符串的json_encode计算结果为"\"\""

In Gson it returns ""

在 Gson 中它返回 ""

回答by Vivek Chaudhari

json_encode in php is similar to following package in java

php 中的 json_encode 类似于 java 中的以下包

dependency:

依赖:

import com.fasterxml.Hymanson.databind.ObjectMapper;

code :

代码 :

Map<Object,Object> dataArray = {some data in map}
ObjectMapper objMapper = new ObjectMapper();
String jsonString = objMapper.writeValueAsString(dataArray);

jsonString is if the final result like son_encode in php, which you can achieve with objectMapper class

jsonString 是最后的结果,如php中的son_encode,可以用objectMapper类实现

回答by Quentin

There is a list of several Java libraries that handle JSON encoding at the bottom of http://json.org/— take your pick.

http://json.org/的底部有一个处理 JSON 编码的 Java 库的列表——任你选择。