如何从Java servlet返回JSON对象。
以前,在使用servlet执行AJAX时,我返回了一个字符串。是否有需要使用的JSON对象类型,或者只返回一个看起来像JSON对象的字符串,例如
String objectToReturn = "{ key1: 'value1', key2: 'value2' }";
发布于 2010-01-06 12:42:30
我完全按照您的建议做(返回一个String
)。
不过,您可以考虑设置MIME类型,以指示将返回JSON (根据this other stackoverflow post,它是“应用程序/json”)。
发布于 2010-01-06 17:44:57
将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();
发布于 2017-01-16 14:46:40
我使用Jackson将Java Object转换为JSON string,并按如下方式发送。
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();
https://stackoverflow.com/questions/2010990
复制相似问题