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();
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.put("Mobile", 9999988888);
json.put("Name", "ManojSarnaik");
// finally output the json string
out.print(json.toString());
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);
11 回答
我完全按照你的建议(返回
String
) .您可以考虑设置MIME类型以指示您正在返回JSON(根据this other stackoverflow post它是"application/json") .
将JSON对象写入响应对象的输出流 .
您还应该按如下方式设置内容类型,该类型将指定您要返回的内容:
首先将JSON对象转换为
String
. 然后将其写入响应编写器以及application/json
的内容类型和UTF-8的字符编码 .这里's an example assuming you'使用Google Gson将Java对象转换为JSON字符串:
就这样 .
另见:
How to use Servlets and Ajax?
What is the correct JSON content type?
只需在输出流中写一个字符串即可 . 你可以将MIME类型设置为
text/javascript
( edit :application/json
显然是官方的),如果你是一个很小但非零的机会,它是一个很好的做法 . )Gson对此非常有用 . 更容易均匀 . 这是我的例子:
}
不得不说人们,如果你的vars是空的,当使用gson它不会为你 Build json . 就是这样
可能有一个JSON对象可以方便Java编码 . 但最后数据结构将序列化为字符串 . 设置正确的MIME类型会很好 .
我建议从json.org JSON Java .
我使用Jackson将Java Object转换为JSON字符串并发送如下 .
response.setContentType( “文本/ JSON”);
//创建JSON字符串,我建议使用一些框架 .
String your_string;
out.write(your_string.getBytes( “UTF-8”));
接近BalusC使用Google Gson lib在4个简单的行中回答 . 将此行添加到servlet方法:
祝好运!
根据Java版本(或JDK,SDK,JRE ...我不知道,我是Java生态系统的新手),
JsonObject
是抽象的 . 所以,这是一个新的实现: