使用fastJson
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.28</version>
</dependency>
1.get json数据
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//封装数据
User u = new User();
u.setUid(1);
u.setUserName("lwx");
DataObject dataObject = new DataObject();
dataObject.setId(1);
dataObject.setMessage("data");
Date date = new Date();
dataObject.setDate(date);
dataObject.setUser(u);
/**
* date类型直接转json是毫秒形式
* 1、后端处理 JSONConfig
* 2. js处理 date = new Date(date).toLocaleString();
*/
String json = JSON.toJSONString(dataObject);
System.out.println(json);
resp.setContentType("text/json;charset=utf-8");
resp.getWriter().write(json);
}
前端ajax获取的date是毫秒数,js转化一下
$.ajax({
url : 'test',
type : 'get',
success(res){
console.log(res);
res.date = new Date(res.date).toLocaleString();
console.log(res.date)
}
})
2. post json数据
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
BufferedReader reader = req.getReader();
String jsonStr = reader.readLine();
JSONObject data=JSONObject.parseObject(jsonStr);
reader.close();
int id = data.getInteger("id");
String message = data.getString("message");
Date date = data.getDate("date");
System.out.println(id + " " + message + " " + date);
}
$("#btn").click(function (){
var date = new Date();
console.log(date);
var list = {
id : 1,
message : "str",
date : date
}
$.ajax({
url : '/test',
type : 'post',
contentType : "application/json",
dataType : "json",
data : JSON.stringify(list),
success(res){
}
})
})
标签:处理,res,dataObject,Date,json,date,new,servlet
From: https://www.cnblogs.com/lwx11111/p/16927340.html