2

BeanIO 参考指南指出,对于固定长度的流:

如果 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 个空格被解组为一个空字符串。我错过了什么?如何将空格解组为空字符串?

4

1 回答 1

3

最后,我使用基于StringTypeHandler的类型处理程序解决了这个问题:

@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 组的用户建议,也可以trim=true, lazy=true@Field注释上使用:

    @Field(length = 5, trim = true, lazy = true) 
    String field;
于 2016-01-04T14:20:25.417 回答