Jackson 是否可以配置为从所有字符串属性中修剪前导/尾随空格? [英] Can Jackson be configured to trim leading/trailing whitespace from all string properties?

查看:39
本文介绍了Jackson 是否可以配置为从所有字符串属性中修剪前导/尾随空格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例 JSON(注意字符串有尾随空格):

Example JSON (note that the string has trailing spaces):

{ "aNumber": 0, "aString": "string   " }

理想情况下,反序列化的实例将有一个 aString 属性,其值为 "string"(即没有尾随空格).这似乎是可能受支持的东西,但我找不到它(例如在 DeserializationConfig.Feature 中).

Ideally, the deserialised instance would have an aString property with a value of "string" (i.e. without trailing spaces). This seems like something that is probably supported but I can't find it (e.g. in DeserializationConfig.Feature).

我们使用的是 Spring MVC 3.x,因此基于 Spring 的解决方案也可以.

We're using Spring MVC 3.x so a Spring-based solution would also be fine.

我尝试根据 论坛帖子中的建议配置 Spring 的 WebDataBinder 但在使用 Jackson 消息转换器时似乎不起作用:

I tried configuring Spring's WebDataBinder based on a suggestion in a forum post but it does not seem to work when using a Jackson message converter:

@InitBinder
public void initBinder( WebDataBinder binder )
{
    binder.registerCustomEditor( String.class, new StringTrimmerEditor( " 	
f", true ) );
}

推荐答案

With a 自定义反序列化器,您可以执行以下操作:

With a custom deserializer, you could do the following:

 <your bean>
 @JsonDeserialize(using=WhiteSpaceRemovalSerializer.class)
 public void setAString(String aString) {
    // body
 }

 <somewhere>
 public class WhiteSpaceRemovalDeserializer extends JsonDeserializer<String> {
     @Override
     public String deserialize(JsonParser jp, DeserializationContext ctxt) {
         // This is where you can deserialize your value the way you want.
         // Don't know if the following expression is correct, this is just an idea.
         return jp.getCurrentToken().asText().trim();
     }
 }

此解决方案确实意味着此 bean 属性将始终以这种方式序列化,并且您必须注释要以这种方式反序列化的每个属性.

This solution does imply that this bean attribute will always be serialized this way, and you will have to annotate every attribute that you want to be deserialized this way.

这篇关于Jackson 是否可以配置为从所有字符串属性中修剪前导/尾随空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆