![](/img/trans.png)
[英]How to serialize Java object into JSON and return it in servlet filter?
[英]How do you return a JSON object from a Java Servlet
您如何从 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();
首先将 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 Object 转换为 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();
只需将字符串写入输出流。 如果您觉得有帮助,您可以将 MIME 类型设置为text/javascript
( edit : application/json
显然是官方的)。 (有一个很小但非零的机会,它可以防止某天将某些东西弄乱,这是一个很好的做法。)
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);
{"nombre":"juan","apellido":"machado","datosCriticos":[{"edad":12}]}
不得不说,如果你的变量在使用 gson 时为空,它不会为你构建 json。只是
{}
可能有一个 JSON 对象以方便 Java 编码。 但最终数据结构将被序列化为字符串。 设置适当的 MIME 类型会很好。
我建议从json.org 使用JSON Java 。
根据 Java 版本(或 JDK、SDK、JRE...我不知道,我是 Java 生态系统的新手), 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字符串,我建议使用一些框架。
字符串 your_string;
out.write(your_string.getBytes("UTF-8"));
你可以使用波纹管之类的。
如果你想使用 json 数组:
创建一个名为Model 的类,如下所示
public class Model { private String id = ""; private String name = ""; //getter sertter here }
在 sevlet getMethod 中,您可以像下面这样使用
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //begin get data from databse or other source List<Model> list = new ArrayList<>(); Model model = new Model(); model.setId("101"); model.setName("Enamul Haque"); list.add(model); Model model1 = new Model(); model1.setId("102"); model1.setName("Md Mohsin"); list.add(model1); //End get data from databse or other source try { JSONArray ja = new JSONArray(); for (Model m : list) { JSONObject jSONObject = new JSONObject(); jSONObject.put("id", m.getId()); jSONObject.put("name", m.getName()); ja.add(jSONObject); } System.out.println(" json ja = " + ja); response.addHeader("Access-Control-Allow-Origin", "*"); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); response.getWriter().print(ja.toString()); response.getWriter().flush(); } catch (Exception e) { e.printStackTrace(); } }
输出:
[{"name":"Enamul Haque","id":"101"},{"name":"Md Mohsin","id":"102"}]
我你想要 json 对象就像这样使用:
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
JSONObject json = new JSONObject();
json.put("id", "108");
json.put("name", "Enamul Haque");
System.out.println(" json JSONObject= " + json);
response.addHeader("Access-Control-Allow-Origin", "*");
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().print(json.toString());
response.getWriter().flush();
// System.out.println("Response Completed... ");
} catch (Exception e) {
e.printStackTrace();
}
}
以上函数输出:
{"name":"Enamul Haque","id":"108"}
完整源码提供给 GitHub: https : //github.com/enamul95/ServeletJson.git
使用 Google Gson 库以 4 行简单的方式接近BalusC答案。 将此行添加到 servlet 方法:
User objToSerialize = new User("Bill", "Gates");
ServletOutputStream outputStream = response.getOutputStream();
response.setContentType("application/json;charset=UTF-8");
outputStream.print(new Gson().toJson(objToSerialize));
祝你好运!
通过使用 Gson,您可以发送 json 响应,请参见下面的代码
你可以看到这个代码
@WebServlet(urlPatterns = {"/jsonResponse"})
public class JsonResponse extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
Student student = new Student(12, "Ram Kumar", "Male", "1234565678");
Subject subject1 = new Subject(1, "Computer Fundamentals");
Subject subject2 = new Subject(2, "Computer Graphics");
Subject subject3 = new Subject(3, "Data Structures");
Set subjects = new HashSet();
subjects.add(subject1);
subjects.add(subject2);
subjects.add(subject3);
student.setSubjects(subjects);
Address address = new Address(1, "Street 23 NN West ", "Bhilai", "Chhattisgarh", "India");
student.setAddress(address);
Gson gson = new Gson();
String jsonData = gson.toJson(student);
PrintWriter out = response.getWriter();
try {
out.println(jsonData);
} finally {
out.close();
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.