解析请求中的 json 数据,返回 json 数据
1. 加入 Gson.jar 包
2. 通过输入流读取数据,使用 Gson 对象解析字符串
-
protected void requestBodyJSON(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 1.由于请求体数据有可能很大,所以Servlet标准在设计API的时候要求我们通过输入流来读取 BufferedReader reader = request.getReader(); // 2.创建StringBuilder对象来累加存储从请求体中读取到的每一行 StringBuilder builder = new StringBuilder(); // 3.声明临时变量 String bufferStr = null; // 4.循环读取 while((bufferStr = reader.readLine()) != null) { builder.append(bufferStr); } // 5.关闭流 reader.close(); // 6.累加的结果就是整个请求体 String requestBody = builder.toString(); // 7.创建Gson对象用于解析JSON字符串 Gson gson = new Gson(); // 8.将JSON字符串还原为Java对象 Student student = gson.fromJson(requestBody, Student.class); System.out.println("student = " + student); System.out.println("requestBody = " + requestBody); response.setContentType("text/html;charset=UTF-8"); response.getWriter().write("服务器端返回普通文本字符串作为响应"); }
3. 服务器封装 json 数据发送给客户端
-
protected void responseBodyJSON(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 1.准备数据对象 Student student = new Student(); student.setStuId(10); student.setStuName("tom"); student.setSchool(new School(11,"atguigu")); student.setSubjectList(Arrays.asList(new Subject("java", 95.5), new Subject("php", 93.3))); Map<String, Teacher> teacherMap = new HashMap<>(); teacherMap.put("t1", new Teacher("lili", 25)); teacherMap.put("t2", new Teacher("mary", 26)); teacherMap.put("t3", new Teacher("katty", 27)); student.setTeacherMap(teacherMap); // 2.创建Gson对象 Gson gson = new Gson(); // 3.将Java对象转换为JSON对象 String json = gson.toJson(student); // 4.设置响应体的内容类型 response.setContentType("application/json;charset=UTF-8"); response.getWriter().write(json); }