如何从 Java Servlet 返回 JSON 对象

2022-08-31 07:10:49

如何从 Java servlet 返回 JSON 对象。

以前,当使用 servlet 执行 AJAX 时,我返回了一个字符串。是否存在需要使用的 JSON 对象类型,或者您只是返回一个看起来像 JSON 对象的字符串,例如

String objectToReturn = "{ key1: 'value1', key2: 'value2' }";

答案 1

将 JSON 对象写入响应对象的输出流。

您还应该按如下方式设置内容类型,这将指定要返回的内容:

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();

答案 2

首先将 JSON 对象转换为 。然后只需将其与 UTF-8 的内容类型和字符编码一起写给响应编写器即可。Stringapplication/json

下面是一个示例,假设您使用 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);
}

就这样。

另请参阅: