(1)核心
1.设置content-type为application/json
2.直接作为数据使用输出流进行输出
(2)实例
package com.learn.servlet;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.alibaba.fastjson.JSON;
public class JsonServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private User buildUserDO(){
User user = new User();
user.setName("张三");
user.setPassword("123");
user.setAge(11);
user.setBirthDay(new Date());
return user;
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("application/json; charset=utf-8");
response.setCharacterEncoding("UTF-8");
String userJson = JSON.toJSONString(buildUserDO());
OutputStream out = response.getOutputStream();
out.write(userJson.getBytes("UTF-8"));
out.flush();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
运行结果为: