applicationContext.xml
1 <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> 2 <property name="messageConverters"> 3 <list> 4 <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> 5 <property name="supportedMediaTypes"> 6 <list> 7 <value>text/plain;charset=UTF-8</value> 8 <value>application/json;charset=UTF-8</value> 9 </list> 10 </property> 11 <property name="objectMapper"> 12 <bean class="com.charmyin.cmstudio.common.utils.ObjectMappingCustomer"></bean> 13 </property> 14 </bean> 15 </list> 16 </property> 17 </bean>
此处我也尝试了
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> ...... </bean>
ObjectMappingCustomer.java
1 package com.charmyin.cmstudio.common.utils; 2 3 4 import java.io.IOException; 5 6 import com.fasterxml.jackson.databind.JsonSerializer; 7 import com.fasterxml.jackson.databind.ObjectMapper; 8 import com.fasterxml.jackson.core.JsonGenerator; 9 import com.fasterxml.jackson.core.JsonParser; 10 import com.fasterxml.jackson.core.JsonProcessingException; 11 import com.fasterxml.jackson.databind.SerializerProvider; 12 13 public class ObjectMappingCustomer extends ObjectMapper 14 15 { 16 17 /** 18 * 19 */ 20 private static final long serialVersionUID = 1L; 21 22 23 24 public ObjectMappingCustomer() 25 26 { 27 // 28 super(); 29 30 // 允许单引号 31 32 this.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); 33 34 // 字段和值都加引号 35 36 this.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true); 37 38 // 数字也加引号 39 40 this.configure(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS, true); 41 42 this.configure(JsonGenerator.Feature.QUOTE_NON_NUMERIC_NUMBERS, true); 43 // 44 // // 空值处理为空串 45 // 46 SerializerProvider sp = (SerializerProvider) this.getSerializerProvider(); 47 48 sp.setNullValueSerializer(new JsonSerializer<Object>(){ 49 50 51 52 @Override 53 54 public void serialize(Object value, JsonGenerator jg, 55 56 SerializerProvider sp) throws IOException, 57 58 JsonProcessingException { 59 60 jg.writeString(""); 61 62 } 63 64 65 66 }); 67 // 68 // 69 // 70 } 71 72 }
输出的json
{ "rows": [ { "pageVO": null, "praId": "bffa397b245849909a9c2af4e74e007d19a1e6cb", "creatorId": 248, "creatorName": "stu123", "finalReport": null } ] }