Spring mvc jackson输出null为空字符串、单引号、字段和数字加引号问题Spring mvc3 jackson输出null为空字符串、单引号、字段和数字加引号问题

最近做项目,和其他人商议用json通信,因为对方是php程序员,php的编码风格对于java程序员来说就是变态,有几点变态需求:

1、json requestbody 输要用单引号(jackson默认是双引号,单引号直接报错)

2、responsebody数字输出要加引号,字段名要加引号。

3、null值为空串

 

于是查阅官方文档,终于找到方法,有点小搓,直接在Converter对象上注入一个自定义类ObjectMappingCustomer:

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.MappingJacksonHttpMessageConverter">  
  5.                    <property name="supportedMediaTypes">  
  6.                        <list>  
  7.                            <value>text/plain;charset=UTF-8value>  
  8.                            <value>application/json;charset=UTF-8value>  
  9.                        list>  
  10.                    property>  
  11.                    <property name="objectMapper">  
  12.                        <bean class="com.wuliaolll.util.ObjectMappingCustomer">bean>  
  13.                    property>  
  14.                bean>     
  15.            list>     
  16.        property>     
  17.    bean>     

 

Java代码  
  1. package com.wuliaolll.util;  
  2.   
  3. import java.io.IOException;  
  4.   
  5. import org.codehaus.jackson.JsonGenerator;  
  6. import org.codehaus.jackson.JsonParser;  
  7. import org.codehaus.jackson.JsonProcessingException;  
  8. import org.codehaus.jackson.map.JsonSerializer;  
  9. import org.codehaus.jackson.map.ObjectMapper;  
  10. import org.codehaus.jackson.map.SerializerProvider;  
  11.   
  12. public class ObjectMappingCustomer extends ObjectMapper  
  13. {  
  14.   
  15.     public ObjectMappingCustomer()  
  16.     {  
  17.         super();  
  18.         // 允许单引号  
  19.         this.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);  
  20.         // 字段和值都加引号  
  21.         this.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);  
  22.         // 数字也加引号  
  23.         this.configure(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS, true);  
  24.         this.configure(JsonGenerator.Feature.QUOTE_NON_NUMERIC_NUMBERS, true);  
  25.         // 空值处理为空串  
  26.         this.getSerializerProvider().setNullValueSerializer(new JsonSerializer()  
  27.         {  
  28.   
  29.             @Override  
  30.             public void serialize(  
  31.                     Object value,  
  32.                     JsonGenerator jg,  
  33.                     SerializerProvider sp) throws IOException, JsonProcessingException  
  34.             {  
  35.                 jg.writeString("");  
  36.             }  
  37.         });  
  38.   
  39.     }  
  40. }  
  41. 你可能感兴趣的:(spring,mvc)