1.因为StringSerializer有final修饰,所以拷一份
com.fasterxml.jackson.databind.ser.std.StringSerializer,对里面的serializeWithType方法做下改写,根据没有没传入转繁体字请求头,确定要不要把中文转成繁体
@JacksonStdImpl
public final class MyStringSerializer extends StdScalarSerializer<Object> implements ContextualSerializer {
private static final long serialVersionUID = 1L;
public MyStringSerializer() {
super(String.class, false);
}
.....................
@Override
public final void serializeWithType(Object value, JsonGenerator gen, SerializerProvider provider,
TypeSerializer typeSer) throws IOException {
// no type info, just regular serialization
genStr(value, gen);
}
.........................
private void genStr(Object value, JsonGenerator gen) throws IOException {
// 查看上下文中有没有返回简体或繁体的标识
String strValue = (String) value;
gen.writeString(needFTZ() ? DrinStringUtils.toFTZ(strValue) : strValue);
}
private boolean needFTZ() {
HttpServletRequest request = getRequest();
if (null == request) {
return false;
}
String ftzFlag = request.getHeader(StaticValue.STATIC_JT_OR_FT);
// 如果不为空且等于1,所有接口返回的汉字都是简体
return DrinStringUtils.isNotNull(ftzFlag) && StaticValue.STATIC_ONE.equals(String.valueOf(ftzFlag));
}
private HttpServletRequest getRequest() {
try {
return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
} catch (Exception e) {
return null;
}
}
private String toFTZ(String jtz) {
return ZHConverter.convert(jtz, ZHConverter.TRADITIONAL);
}
}
2.写一个自定义的BeanSerializerFactory,把里面的默认string序列化类替换掉。
public class MyBeanSerializerFactory extends BeanSerializerFactory {
private static final long serialVersionUID = 1L;
public MyBeanSerializerFactory(SerializerFactoryConfig config) {
super(config);
// 强行替换父类里面的字符串序列化工具
_concrete.put(String.class.getName(), new MyStringSerializer());
}
}
3:定义一个ObjectMapper bean,将SerializerFactory替换
@Bean
public ObjectMapper createObjectMapper() {
ObjectMapper objectMapper = new ObjectMapper();
// 时区
objectMapper.setTimeZone(TimeZone.getTimeZone("GMT+8"));
// 对空值的处理
objectMapper.setDefaultPropertyInclusion(JsonInclude.Include.ALWAYS);
// 替换默认的序列化工厂,把对字符串的转换设置成自定义带繁简的序列化工具
objectMapper.setSerializerFactory(new MyBeanSerializerFactory(null));
// 设置重写了parse方法的日期format
objectMapper.setDateFormat(new MySimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
return objectMapper;
}