layout: blog
istop: true
title: “spring-json全局序列化”
date: 2018-08-07
category: spring
tags:
后台传送数据给前端,一般使用json ,多的不说,看个例子:
如果使用mongodb数据库,非常容易出现一种状况, 在传送ObjectId (默认数据可以的主键)时会发生如下情况:
data :{
objectId :{
timestamp:123123123,
machineIdentifier: 12,
processIdentifier: 12,
counter:5 6,
},
name:“张三”
}
问题出现了,ObjectId 前端只是要我们说传递一个字符串(ObjectId的),而我们却传递了一个对象,前端肯定会(你懂的!!!)
public class ObjectIdSerializer extends JsonSerializer<ObjectId> {
@Override
public void serialize(ObjectId value, JsonGenerator jsonGen,
SerializerProvider provider) throws IOException,
JsonProcessingException {
jsonGen.writeString(value.toString());
}
}
Class User{
@JsonSerialize(using = ObjectIdSerializer.class)
private ObjectId id;
private String name;
}
优势:可以解决问题
缺点:整个项目但凡要 传递给前端的,都需要加入整个注解
全局配置是要带 方式一 第一个步骤的基础之上的,具体操作如下:
@SuppressWarnings("serial")
public class ObjectIdMapper extends ObjectMapper {
public ObjectIdMapper() {
SimpleModule module = new SimpleModule("ObjectIdmodule");
module.addSerializer(ObjectId.class, new ObjectIdSerializer());
this.registerModule(module);
}
}
<bean id="mappingJackson2HttpMessageConverter"
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8value>
list>
property>
bean>
3)springboot 项目,直接加入一个配置bean 就好了,配置如下
@Configuration
public class JsonMessageConverter {
@Bean
public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder){
ObjectMapper objectMapper = builder.createXmlMapper(false).build();
//将json属性的空值null转化为空字符串""
objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
@Override
public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeString("");
}
});
SimpleModule module = new SimpleModule();
module.addSerializer(ObjectId.class, new ObjectIdSerializer());
objectMapper.registerModule(module);
return objectMapper;
}
}
data :{
objectId :"jjaiaiajiaiaiajaldkdkdkdkdkdkdd",
name:“张三”
}
使用的是java序列化的开源jar, Jackson
jackson参见
springboot 修改序列化工具 Jackson 改为 FastJson