示例 JSON(注意字符串有尾随空格):
{ "aNumber": 0, "aString": "string " }
理想情况下,反序列化的实例应该有一个 aString 属性,其值为 "string"(即没有尾随空格)。这似乎是可能受支持的东西,但我找不到它(例如在 DeserializationConfig.Feature 中)。
我们使用的是 Spring MVC 3.x,因此基于 Spring 的解决方案也可以。
我尝试根据 forum post 中的建议配置 Spring 的 WebDataBinder但是在使用 Jackson 消息转换器时它似乎不起作用:
@InitBinder
public void initBinder( WebDataBinder binder )
{
binder.registerCustomEditor( String.class, new StringTrimmerEditor( " \t\r\n\f", true ) );
}
最佳答案
Spring Boot 用户的简单解决方案,只需将 walv 的 SimpleModule 扩展添加到您的应用程序上下文中:
package com.example;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.deser.std.StdScalarDeserializer;
import com.fasterxml.jackson.databind.module.SimpleModule;
import org.springframework.stereotype.Component;
import java.io.IOException;
@Component
public class StringTrimModule extends SimpleModule {
public StringTrimModule() {
addDeserializer(String.class, new StdScalarDeserializer<String>(String.class) {
@Override
public String deserialize(JsonParser jsonParser, DeserializationContext ctx) throws IOException,
JsonProcessingException {
return jsonParser.getValueAsString().trim();
}
});
}
}
Another way to customize Jackson is to add beans of type com.fasterxml.jackson.databind.Module to your context. They will be registered with every bean of type ObjectMapper, providing a global mechanism for contributing custom modules when you add new features to your application.
http://docs.spring.io/spring-boot/docs/current/reference/html/howto-spring-mvc.html#howto-customize-the-jackson-objectmapper
如果你不使用spring boot,你必须自己注册StringTrimModule(你不需要用@Component注解它)
<bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
<property name="modulesToInstall" value="com.example.StringTrimModule"/>
</bean
https://stackoverflow.com/questions/6852213/