springmvc的json 乱码处理
@ResponseBody 不会执行跳转到视图
@RequestMapping(value = “/j1” ,produces = “application/json;charset=utf-8”)
这个是防止乱码的
@RestController
//@Controller
public class UserController {
@RequestMapping(value = "/j1" ,produces = "application/json;charset=utf-8")
//@ResponseBody
public String json1() throws JsonProcessingException {
//jackson ObjectMapper
ObjectMapper mapper = new ObjectMapper();
User user = new User("李少",18,"男");
String str = mapper.writeValueAsString(user);
return str;
}
用这个@RestController就不能用//@ResponseBody
时间戳工具类
@RequestMapping("/j3")
public String jsonData(){
Date data = new Date();
return JsonUtils.getJson(data);
}
}
package com.lishao.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_DATES_AS_TIMESTAMPS, false);
//自定义日期格式对象
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
//指定日期格式
mapper.setDateFormat(sdf);
try {
return mapper.writeValueAsString(object);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
}
用这个工具类可以自己规定时间格式
省时省力