如何从Java Servlet返回JSON对象

168

如何从Java servlet返回JSON对象。

之前在使用servlet进行AJAX时,我返回了一个字符串。是否需要使用JSON对象类型,或者只需返回类似于JSON对象的字符串,例如:

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

10
你是不是想要更多像 { key1: value1, key2: value2 } 这样的内容呢?Nitpick 的含义是挑剔,可能在这里是指一些微小的问题或建议。 - user240438
16
吹毛求疵的人想要的是 { "key1": "value1", "key2": "value2" }... :-) - PhiLho
如果您决定使用Spring 3.2.0,请查看以下链接:@Ankur checkout the link - AmirHd
5
挑剔一点:我们不应该假定这些值是字符串,所以他真正想要的是{ "key1": value1, "key2": value2 }。 - NoBrainer
这些吹毛求疵的细节(特别是按照这个顺序),真是史诗级的 :) - Ankur
13个回答

181

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

7
这对我很有帮助。正如马克·艾略特的回答中所提到的那样,** jsonObject **可以只是格式化为JSON的字符串。请记得使用双引号,因为单引号不会给您一个有效的JSON。例如:String jsonStr = "{\"my_key\": \"my_value\"}"; - marcelocra
3
使用response.setCharacterEncoding("utf-8");也是很好的。 - erhun

89

首先将JSON对象转换为String。然后,将其与application/json的内容类型以及UTF-8字符编码一起写入响应写入器中。

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

这就是全部。

另请参阅:


我这样做是为了向JavaScript发送响应并在警报中显示响应。为什么它在警报中显示HTML代码..为什么我会得到HTML代码作为响应。我按照你说的完全一样的方式去做了。 - Abhi
我和@iLive有相同的问题。 - Wax

57

我完全按照你的建议执行(返回一个 String)。

不过,你可以考虑设置MIME类型来指示你正在返回JSON(根据这篇其他的stackoverflow文章,应该是“application/json”)。


34

如何从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());

根据版本不同,JsonObject可能是抽象的。我创建了一个针对新实现的答案。 - Rafael Barros

13

我使用Jackson将Java对象转换为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();

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

{"name":"juan","surname":"machado","criticalData":[{"age":12}]}

When using Gson, if your variables are empty, the JSON will not be generated. Only the following will be printed:

{}


8

只需要将字符串写入输出流中。如果你感到有帮助,可以设置MIME类型为text/javascript编辑:显然官方更推荐application/json)。这样做可能会在未来避免某些问题,并且是一个很好的实践。


7

根据Java版本(或JDK、SDK、JRE...我不知道,我还是新手),JsonObject可能是抽象的。所以,这是一个新的实现:

import javax.json.Json;
import javax.json.JsonObject;

...

try (PrintWriter out = response.getWriter()) {
    response.setContentType("application/json");       
    response.setCharacterEncoding("UTF-8");

    JsonObject json = Json.createObjectBuilder().add("foo", "bar").build();

    out.print(json.toString());
}

7

为了方便Java编码,可能会使用JSON对象。但最终数据结构将被序列化为字符串。设置适当的MIME类型会很好。

我建议使用JSON Java来自json.org


不正确。通常没有必要增加构造String的开销--输出应直接到达OutputStream。或者,如果由于某种原因需要中间形式,则可以使用byte[]。大多数Java JSON库都可以直接写入OutputStream - StaxMan

3

response.setContentType("text/json");

//创建JSON字符串,我建议使用一些框架。

String your_string;

out.write(your_string.getBytes("UTF-8"));

注:该代码段设置响应的内容类型为文本/JSON格式,并将JSON字符串写入输出流中。建议使用框架来创建JSON字符串。

我需要使用getBytes("UTF-8")吗?还是可以直接返回String变量? - Ankur
在Web应用程序中,使用UTF-8对响应进行编码是一种安全的编程实践。 - RHT

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接