如何从 Java Servlet 返回 JSON 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2010990/
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
How do you return a JSON object from a Java Servlet
提问by Ankur
How do you return a JSON object form a Java servlet.
您如何从 Java servlet 返回 JSON 对象。
Previously when doing AJAX with a servlet I have returned a string. Is there a JSON object type that needs to be used, or do you just return a String that looks like a JSON object e.g.
以前在使用 servlet 执行 AJAX 时,我返回了一个字符串。是否有需要使用的 JSON 对象类型,或者您是否只返回一个看起来像 JSON 对象的字符串,例如
String objectToReturn = "{ key1: 'value1', key2: 'value2' }";
采纳答案by Mark Elliot
I do exactly what you suggest (return a String
).
我完全按照你的建议去做(返回 a String
)。
You might consider setting the MIME type to indicate you're returning JSON, though (according to this other stackoverflow postit's "application/json").
不过,您可能会考虑设置 MIME 类型以指示您正在返回 JSON(根据另一个 stackoverflow 帖子,它是“application/json”)。
回答by Mark Elliot
Just write a string to the output stream. You might set the MIME-type to text/javascript
(edit: application/json
is apparently officialer) if you're feeling helpful. (There's a small but nonzero chance that it'll keep something from messing it up someday, and it's a good practice.)
只需将字符串写入输出流。如果您觉得有帮助,您可以将 MIME 类型设置为text/javascript
( edit:application/json
显然是官方的)。(有一个很小但非零的机会,它可以防止某天将某些东西弄乱,这是一个很好的做法。)
回答by nil
There might be a JSON object for Java coding convenience. But at last the data structure will be serialized to string. Setting a proper MIME type would be nice.
可能有一个 JSON 对象以方便 Java 编码。但最终数据结构将被序列化为字符串。设置适当的 MIME 类型会很好。
I'd suggest JSON Javafrom json.org.
我建议从json.org 使用JSON Java。
回答by RHT
response.setContentType("text/json");
response.setContentType("text/json");
//create the JSON string, I suggest using some framework.
//创建JSON字符串,我建议使用一些框架。
String your_string;
字符串 your_string;
out.write(your_string.getBytes("UTF-8"));
out.write(your_string.getBytes("UTF-8"));
回答by user241924
Write the JSON object to the response object's output stream.
将 JSON 对象写入响应对象的输出流。
You should also set the content type as follows, which will specify what you are returning:
您还应该按如下方式设置内容类型,这将指定您要返回的内容:
response.setContentType("application/json");
// Get the printwriter object from response to write the required json object to the output stream
PrintWriter out = response.getWriter();
// Assuming your json object is **jsonObject**, perform the following, it will return your json object
out.print(jsonObject);
out.flush();
回答by BalusC
First convert the JSON object to String
. Then just write it out to the response writer along with content type of application/json
and character encoding of UTF-8.
首先将 JSON 对象转换为String
. 然后只需将其与application/json
UTF-8 的内容类型和字符编码一起写给响应编写器。
Here's an example assuming you're using Google Gsonto convert a Java object to a JSON string:
这是一个假设您使用Google Gson将 Java 对象转换为 JSON 字符串的示例:
protected void doXxx(HttpServletRequest request, HttpServletResponse response) {
// ...
String json = new Gson().toJson(someObject);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
}
That's all.
就这样。
See also:
也可以看看:
回答by superUser
Gson is very usefull for this. easier even. here is my example:
Gson 对此非常有用。甚至更容易。这是我的例子:
public class Bean {
private String nombre="juan";
private String apellido="machado";
private List<InnerBean> datosCriticos;
class InnerBean
{
private int edad=12;
}
public Bean() {
datosCriticos = new ArrayList<>();
datosCriticos.add(new InnerBean());
}
}
}
Bean bean = new Bean();
Gson gson = new Gson();
String json =gson.toJson(bean);
out.print(json);
{"nombre":"juan","apellido":"machado","datosCriticos":[{"edad":12}]}
out.print(json);
{"nombre":"juan","apellido":"machado","datosCriticos":[{"edad":12}]}
Have to say people if yours vars are empty when using gson it wont build the json for you.Just the
不得不说,如果你的变量在使用 gson 时为空,它不会为你构建 json。只是
{}
{}
回答by MAnoj Sarnaik
How do you return a JSON object from a Java Servlet
如何从 Java Servlet 返回 JSON 对象
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
//create Json Object
JsonObject json = new JsonObject();
// put some value pairs into the JSON object .
json.addProperty("Mobile", 9999988888);
json.addProperty("Name", "ManojSarnaik");
// finally output the json string
out.print(json.toString());
回答by Panayot Kulchev
Close to BalusCanswer in 4 simple lines using Google Gson lib. Add this lines to the servlet method:
使用 Google Gson 库以 4 行简单的方式接近BalusC答案。将此行添加到 servlet 方法:
User objToSerialize = new User("Bill", "Gates");
ServletOutputStream outputStream = response.getOutputStream();
response.setContentType("application/json;charset=UTF-8");
outputStream.print(new Gson().toJson(objToSerialize));
Good luck!
祝你好运!
回答by ravthiru
I used Hymansonto convert Java Object to JSON string and send as follows.
我使用Hymanson将 Java Object 转换为 JSON 字符串并发送如下。
PrintWriter out = response.getWriter();
ObjectMapper objectMapper= new ObjectMapper();
String jsonString = objectMapper.writeValueAsString(MyObject);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
out.print(jsonString);
out.flush();