BeanIO - 在编组以固定宽度文件时禁用填充或跳过字段(如果为空)

BeanIO - Disable padding or skip field if null when marshaling to fix width file

我正在尝试使用 BeanIO 库编写固定宽度的文件。这是有问题的记录:

@Record
open class KeySegment(
    @Field(at = 0, length = 1, required = true) var recordType: String = "",
    @Field(at = 1, length = 6, required = true) var primaryCorpId: String = "",
    @Field(at = 7, length = 16, minOccurs = 0) var creditCardAcc: String? = null,
    @Field(at = 7, length = 8, minOccurs = 0) var companyId: String? = null,
    @Field(at = 15, length = 8, minOccurs = 0) var sublevelId: String? = null,
    @Field(at = 23, length = 8, required = true) var fileCreateDate: String = "",
    @Field(at = 31, length = 8) var sourceId: String = "",
    @Field(at = 39, length = 816) var filler: String = ""
)

请注意 creditCardAcccompanyId + sublevelId 在文件中的位置相同。根据用例,我们设置 creditCardAcc 字段或 companyIdsublevelId。现在对于我的用例,我想设置 creditCardAcc,但问题是 companyIdsublevelId 被 space 填充并覆盖 creditCardAcc 字段甚至如果它们设置为 null.

一个解决方案是将这些字段拉入两个扩展 KeySegment 的子类中,然后编组子类。但是,我想知道是否有更好的本机解决方案可用于实现此目的。例如,如果字段为空,是否有办法禁用填充?

谢谢。

当字段为 null 时,无法禁用填充。 padding 属性具有以下描述 here

If padding is enabled, the required field attribute has some control over the marshalling and unmarshalling of null values.

When unmarshalling a field consisting of all spaces in a fixed length stream, if required is false, the field is accepted regardless of the padding character. If required is true, a required field validation error is triggered. And when marshalling a null field value, if required is false, the field text is formatted as spaces regardless of the configured padding character.

引用的最后一句话正是您要问的。