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

时间:2015-12-16 10:08:31

标签: java bean-io

BeanIO reference guide表示对于固定长度的流:

  

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

1 个答案:

答案 0 :(得分:2)

最后,我使用基于type handlerStringTypeHandler来解决此问题:

@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上的用户,还可以在trim=true, lazy=true注释上使用@Field

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