【问题标题】:Unmarshal blank strings to null with BeanIO使用 BeanIO 将空白字符串解组为 null
【发布时间】:2015-12-16 10:08:31
【问题描述】:

BeanIO reference guide 声明对于固定长度的流:

如果 required 设置为 false,则无论填充字符如何,都会将空格解组为空字段值。

所以如果我对这句话的理解正确,就说明这个pojo应该通过下面的测试:

@Record
public class Pojo {

    @Field(length = 5, required = false)
    String field;

    // constructor, getters, setters
}

测试:

@Test
public void test(){

    StreamFactory factory = StreamFactory.newInstance();
    factory.define(new StreamBuilder("pojo")
    .format("fixedlength")
    .addRecord(Pojo.class));

    Unmarshaller unmarshaller = factory.createUnmarshaller("pojo");

    Pojo pojo = (Pojo) unmarshaller.unmarshal("     "); // 5 spaces
    assertNull(pojo.field);

}

但它失败了,这 5 个空格被解组为一个空字符串。我错过了什么?如何将空格解组为空字符串?

【问题讨论】:

    标签: java bean-io


    【解决方案1】:

    最后,我使用基于StringTypeHandlertype handler 解决了这个问题:

    @Test
    public void test(){
    
        StringTypeHandler nullableStringTypeHandler = new StringTypeHandler();
        nullableStringTypeHandler.setNullIfEmpty(true);
        nullableStringTypeHandler.setTrim(true);
    
        StreamFactory factory = StreamFactory.newInstance();
        factory.define(new StreamBuilder("pojo")
            .format("fixedlength")
            .addRecord(Pojo.class)
            .addTypeHandler(String.class, nullableStringTypeHandler)
        );
    
    
        Unmarshaller unmarshaller = factory.createUnmarshaller("pojo");
    
        Pojo pojo = (Pojo) unmarshaller.unmarshal("     ");
        assertNull(pojo.field);
    
    }
    

    更新: 作为beanio-users group suggested 的用户,还可以在@Field 注释上使用trim=true, lazy=true

        @Field(length = 5, trim = true, lazy = true) 
        String field;
    

    【讨论】:

    • trim=truelazy=true 完成这项工作 +1
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-27
    • 2012-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-14
    相关资源
    最近更新 更多