java - 可以将 Jackson 配置为从所有字符串属性中修剪前导/尾随空格吗?

示例 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.Jackson2Objec‌​tMapperFactoryBean">
    <property name="modulesToInstall" value="com.example.StringTrimModule"/>
</bean

https://stackoverflow.com/questions/6852213/

相关文章:

json - Play Framework - 向 JSON 对象添加字段

json - 使用 jq 从 JSON 输出中提取特定字段

ruby-on-rails - 销毁记录时应该渲染什么?

jquery - 使用 jQuery grep() 过滤 JSON 数组

c# - 使用 JSON.NET 序列化/反序列化对象字典

JSON Schema - 根据另一个字段的值指定字段

asp.net-mvc - MVC ajax json 发布到 Controller 操作方法

json - 在 node package.json 中,使用额外参数从另一个脚本调用脚本,在这种情

json - 简单、安全的 API 认证系统

json - 应该如何为 RESTful JSON 集合实现 HATEOAS 样式的链接?