文章目录

之前的php项目全是””空串没有null。。。。。改为java做后台就造成了 这个问题

解决方法和网上的 不太一样 因为SerializerProvider 为StdSerializerProvider的父类,直接从SerializerProvider .setNullValueSerializer()方法 不允许 所以通过子类StdSerializerProvider调用此方法

applicationContext.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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.interceptor.ObjectMappingCustomer"></bean>
</property>
</bean>
</list>
</property>
</bean>

ObjectMappingCustomer.java

package com.interceptor;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
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;
import org.codehaus.jackson.map.ser.StdSerializerProvider;
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);
// 空值处理为空串
StdSerializerProvider sp = (StdSerializerProvider) this.getSerializerProvider();
sp.setNullValueSerializer(new JsonSerializer<Object>(){
@Override
public void serialize(Object value, JsonGenerator jg,
SerializerProvider sp) throws IOException,
JsonProcessingException {
jg.writeString("");
}
});
}
}

然后在springmvc controller里加 @ResponseBody注解就可以了

需要jackson-all.jar

文章目录