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

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

问题描述

示例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.

我尝试根据论坛帖子但是在使用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( " \t\r\n\f", true ) );
}


推荐答案

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

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.

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

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