後臺傳送數據給前端,通常使用json ,多的不說,看個例子:html
若是使用mongodb數據庫,很是容易出現一種情況, 在傳送ObjectId (默認數據能夠的主鍵)時會發生以下狀況:前端
data :{ objectId :{ timestamp:123123123, machineIdentifier: 12, processIdentifier: 12, counter:5 6, }, name:「張三」 }
問題出現了,ObjectId 前端只是要咱們說傳遞一個字符串(ObjectId的),而咱們卻傳遞了一個對象,前端確定會(你懂的!!!)java
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; }
優點:能夠解決問題 <br> 缺點:整個項目但凡要 傳遞給前端的,都須要加入整個註解web
全局配置是要帶 方式一 第一個步驟的基礎之上的,具體操做以下:spring
@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-8</value> </list> </property> <!-- <property name="objectMapper"> <bean class="com.ftf.clw.dsc.web.convert.ObjectIdMapper"></bean> </property> --> </bean>
3)springboot 項目,直接加入一個配置bean 就行了,配置以下mongodb
@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 <br>數據庫
jackson參見 <br> springboot 修改序列化工具 Jackson 改成 FastJson <br>json