使用 BeanIO 将空白字符串解组为 null

Unmarshal blank strings to null with BeanIO

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

if required is set to false, spaces are unmarshalled to a null field value regardless of the padding character.

所以如果我正确理解这句话,这意味着下面的测试应该通过这个 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 个空格被解组为空字符串。我错过了什么?如何将空格解组为空字符串?

最后,我使用 type handler based on 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 group suggested 上的用户,还可以在 @Field 注释上使用 trim=true, lazy=true

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