一、
使用Spring内置的支持,利用spring mvc3的注解@ResponseBody配置的json
其他人商议用json通信,因为对方是php程序员,php的编码风格对于java程序员来说就是变态,有几点变态需求:
1、json requestbody 输要用单引号(jackson默认是双引号,单引号直接报错)
2、responsebody数字输出要加引号,字段名要加引号。
3、null值为空串
于是查阅官方文档,终于找到方法,有点小搓,直接在Converter对象上注入一个自定义类ObjectMappingCustomer:
-
<bean class=\"org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter\">
-
<property name=\"messageConverters\">
-
<list>
-
<bean class=\"org.springframework.http.converter.json.MappingJacksonHttpMessageConverter\">
-
<property name=\"supportedMediaTypes\">
-
<list>
-
<value>text/plain;charset=UTF-8</value>
-
<value>application/json;charset=UTF-8</value>
-
</list>
-
</property>
-
<property name=\"objectMapper\">
-
<bean class=\"com.wuliaolll.util.ObjectMappingCustomer\"></bean>
-
</property>
-
</bean>
-
</list>
-
</property>
-
</bean>
-
package com.wuliaolll.util;
-
-
import java.io.IOException;
-
-
import org.codehaus.jackson.JsonGenerator;
-
import org.codehaus.jackson.JsonParser;
-
import org.codehaus.jackson.JsonProcessingException;
-
import org.codehaus.jackson.map.JsonSerializer;
-
import org.codehaus.jackson.map.ObjectMapper;
-
import org.codehaus.jackson.map.SerializerProvider;
-
-
public class ObjectMappingCustomer extends ObjectMapper
-
{
-
-
public ObjectMappingCustomer()
-
{
-
super();
-
// 允许单引号
-
this.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
-
// 字段和值都加引号
-
this.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
-
// 数字也加引号
-
this.configure(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS, true);
-
this.configure(JsonGenerator.Feature.QUOTE_NON_NUMERIC_NUMBERS, true);
-
// 空值处理为空串
-
this.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>()
-
{
-
-
@Override
-
public void serialize(
-
Object value,
-
JsonGenerator jg,
-
SerializerProvider sp) throws IOException, JsonProcessingException
-
{
-
jg.writeString("");
-
}
-
});
-
-
}
-
}
二、json视图方式
-
<bean class=\"org.springframework.web.servlet.view.json.MappingJacksonJsonView\">
-
<property name=\"encoding\">
-
<value type=\"org.codehaus.jackson.JsonEncoding\">UTF8</value>
-
</property>
-
<property name=\"contentType\" value=\"application/json;charset=UTF-8\"/>
-
</bean>
json:
{"s":{"userId":"1","userName":"测试","passWord":"3","list":null,"dep":null,"date":1325347200000},"userForm":{"userId":"1","userName":"测试","passWord":"3","list":null,"dep":null,"date":1325347200000}}
里面有null值,怎么配置,才能让null自动变成空串
自己构建ObjectMapper注入进去,在ObjectMapper中设置NOT_NULL不转换
<bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView">
<property name="extractValueFromSingleKeyModel" value="true" />
<property name="objectMapper">
<bean class="org.codehaus.jackson.map.ObjectMapper">
<property name="serializationInclusion">
<value type="org.codehaus.jackson.map.annotate.JsonSerialize$Inclusion">NON_NULL</value>
</property>
</bean>
</property>
</bean>
参考自: />
阅读(6915) | 评论(0) | 转发(0) |