使用@ResponseBody注释时,将空值作为空字符串 [英] Null values as empty strings when using @ResponseBody annotation
问题描述
有没有办法在使用 @ResponseBody
注释时将空值映射到空字符串?
Is there a way when using @ResponseBody
annotation to have null values mapped to empty strings?
推荐答案
你必须编写一个自定义的Jackson Serializer - 这是一个很好的例子 - http: //wiki.fasterxml.com/JacksonHowToCustomSerializers (有一个如何将空值转换为可以使用的空字符串的具体示例)
You will have to write a custom Jackson Serializer - a good example is here - http://wiki.fasterxml.com/JacksonHowToCustomSerializers (there is a specific example of how to convert null values to empty Strings that you can use)
这里有所有步骤(对于Jackson< 2.0):
Here are all the steps(for Jackson < 2.0):
编写自定义null序列化器:
Write your custom null Serializer:
import java.io.IOException;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.JsonSerializer;
import org.codehaus.jackson.map.SerializerProvider;
public class NullSerializer extends JsonSerializer<Object> {
@Override
public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
jgen.writeString("");
}
}
使用Jackson Objectmapper注册:
Register this with Jackson Objectmapper:
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.ser.StdSerializerProvider;
public class CustomObjectMapper extends ObjectMapper{
public CustomObjectMapper(){
StdSerializerProvider sp = new StdSerializerProvider();
sp.setNullValueSerializer(new NullSerializer());
this.setSerializerProvider(sp);
}
}
使用Spring MVC注册此objectmapper:
Register this objectmapper with Spring MVC:
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="objectMapper">
<bean class="CustomObjectMapper"/>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
这篇关于使用@ResponseBody注释时,将空值作为空字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!