如何从Java servlet返回JSON对象。
之前在使用servlet进行AJAX时,我返回了一个字符串。是否需要使用JSON对象类型,或者只需返回类似于JSON对象的字符串,例如:
String objectToReturn = "{ key1: 'value1', key2: 'value2' }";
您可以像下面这样使用。
如果您想使用JSON数组:
Create A class named Model like bellow
public class Model {
private String id = "";
private String name = "";
//getter sertter here
}
In sevlet getMethod you can use like bellow
@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();
}
}
Output:
[{"name":"Enamul Haque","id":"101"},{"name":"Md Mohsin","id":"102"}]
@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));
祝你好运!
@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();
}
}
}
从Java Servlet中的JSON响应非常有帮助。
{ key1: value1, key2: value2 }
这样的内容呢?Nitpick 的含义是挑剔,可能在这里是指一些微小的问题或建议。 - user240438