JSON工具类
package com.liu.utils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import java.text.SimpleDateFormat;
public class JsonUtils {
//传一个参数
public static String getJson(Object object){
return getJson(object,"yyyy-MM-dd HH:mm:ss");
}
//传两个参数
public static String getJson(Object object,String dateFormat){
ObjectMapper mapper = new ObjectMapper();
//关闭时间戳的方式
mapper.configure(SerializationFeature.WRITE_DATE_KEYS_AS_TIMESTAMPS,false);
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
mapper.setDateFormat(sdf);
try {
return mapper.writeValueAsString(object);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
}
测试
@RestController//不会走视图解析器
public class UserController {
@RequestMapping("/j1")
public String json1(){
//创建一个对象
User user = new User("刘想",3,"男");
return JsonUtils.getJson(user);
}
结果
配置好tomcat,输入url测试
url:(http://localhost:8080/springmvc_05_json_war_exploded/j1)
结果: