如何从Java servlet返回JSON对象。
之前在使用servlet进行AJAX时,我返回了一个字符串。是否需要使用JSON对象类型,或者只需返回类似于JSON对象的字符串,例如:
String objectToReturn = "{ key1: 'value1', key2: 'value2' }";
将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();
String jsonStr = "{\"my_key\": \"my_value\"}";
- marcelocra首先将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);
}
这就是全部。
我完全按照你的建议执行(返回一个 String
)。
不过,你可以考虑设置MIME类型来指示你正在返回JSON(根据这篇其他的stackoverflow文章,应该是“application/json”)。
如何从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());
我使用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();
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:
{}
只需要将字符串写入输出流中。如果你感到有帮助,可以设置MIME类型为text/javascript
(编辑:显然官方更推荐application/json
)。这样做可能会在未来避免某些问题,并且是一个很好的实践。
根据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());
}
response.setContentType("text/json");
//创建JSON字符串,我建议使用一些框架。
String your_string;
out.write(your_string.getBytes("UTF-8"));
注:该代码段设置响应的内容类型为文本/JSON格式,并将JSON字符串写入输出流中。建议使用框架来创建JSON字符串。
{ key1: value1, key2: value2 }
这样的内容呢?Nitpick 的含义是挑剔,可能在这里是指一些微小的问题或建议。 - user240438