JSON 相关
@ResponseBody把对象以字符串返回。而ObjectMapper.writeValueAsString(o) 把对象转换成json格式的字符串。
此外,Date对象默认转化为时间戳,如果不想要时间戳,参考以下代码进行格式设置。
public class JsonBuilder {
public static String json(Object o) throws JsonProcessingException {
return (new ObjectMapper()).writeValueAsString(o);
}
public static String jsonTime(Object o) throws JsonProcessingException {
return jsonTime(o,"yyyy-MM-dd HH:mm:ss");
}
public static String jsonTime(Object o,String format) throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,false);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
objectMapper.setDateFormat(simpleDateFormat);
return objectMapper.writeValueAsString(o);
}
}
测试代码:
@RestController
@RequestMapping("/json")
public class json {
@RequestMapping("/test")
public String ret(){
User user = new User();
user.setAge(300);
user.setName("AA");
try {
return JsonBuilder.json(user);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
@RequestMapping("/test2")
public String time(){
Date date = new Date();
// date.setTime(System.currentTimeMillis());
try {
return JsonBuilder.jsonTime(date);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
@RequestMapping("/test3")
public String time2(){
Date date = new Date();
// date.setTime(System.currentTimeMillis());
try {
return JsonBuilder.jsonTime(date,"yyyy-dd-MM HH:mm:ss");
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
}
测试结果: