使用@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):
编写您的自定义空序列化程序:
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 中注册这个对象映射器:
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屋!