jackson + spring 支持rest接口,输出的JSON 对于null的字符串是invoiceTitle: null,但是接受方希望返回的是invoiceTitle: ""。解决方法重写ObjectMapper
2.代码如下:
public JsonMapper() { //this(Include.NON_EMPTY); // 空值处理为空串 this.getSerializerProvider().setNullValueSerializer( new JsonSerializer<Object>() { @Override public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { jgen.writeString(""); } }); }
3.配置如下:
<mvc:annotation-driven content-negotiation-manager="contentNegotiationManager"> <mvc:message-converters register-defaults="true"> <!-- 将StringHttpMessageConverter的默认编码设为UTF-8 --> <bean class="org.springframework.http.converter.StringHttpMessageConverter"> <constructor-arg value="UTF-8" /> </bean> <!-- 将Jackson2HttpMessageConverter的默认格式化输出为true --> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="objectMapper"> <bean class="com.sencloud.util.JsonMapper"/> </property> </bean> <!-- 使用XML格式输出数据 --> <bean class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter"> <constructor-arg> <bean class="org.springframework.oxm.xstream.XStreamMarshaller"> <property name="streamDriver"> <bean class="com.thoughtworks.xstream.io.xml.StaxDriver"/> </property> </bean> </constructor-arg> <property name="supportedMediaTypes" value="application/xml"></property> </bean> </mvc:message-converters>
只能通过下面实例实现解决这个问题。
brf.setResultCode(0); brf.setRows(orderBlocks); brf.setResultMessage("succeed"); JsonMapper jsonMapper = new JsonMapper(); return jsonMapper.toJson(brf);
注意使用这种方式需要手动设置编码如下:
@RequestMapping(method = RequestMethod.GET, value = "/test",produces = "application/json; charset=utf-8")
不知为毛,不定位了。
[FAQ]jackson解决:null到"", 空值处理为空串,布布扣,bubuko.com
[FAQ]jackson解决:null到"", 空值处理为空串
原文地址:http://blog.csdn.net/dracotianlong/article/details/29594107