如何使用BeanIO minLength记录级别



我有用于交付文件的beanio映射文件,所需的检查正在进行,但minLength不起作用。你能帮忙吗Geroge人员记录行未显示薪资为空的minLength错误

<record name="detail" minOccurs="0" maxOccurs="unbounded"
class="com.test.Person">
<field name="firstName"/>
<field name="surname"/>
<field name="salary" minLength="1"/>
<field name="age" required="true"/>
</record>

输入:

John|Smith|300000.00|34
Peter|William|800000.00|
Gregory|Rocky||30

输出:

[Person [firstName=John, surname=Smith, salary=300000.0, aget=34], Person [firstName=Gregory, surname=Rocky, salary=0.0, aget=30]]
Errors:
3 : age : [Required field not set]

Java代码:更新

public void readCSVFileUsingBeanIo() throws FileNotFoundException {
StreamFactory factory = StreamFactory.newInstance();
factory.loadResource("person.xml");
StringBuilder rejects = new StringBuilder();
// read it from the classpath : src/main/resources
InputStream in = new FileInputStream(new File(
"person.csv"));
BeanReader reader = factory.createReader("persons", new InputStreamReader(in));
reader.setErrorHandler(new BeanReaderErrorHandlerSupport() {
public void invalidRecord(InvalidRecordException ex) throws Exception {
for (int i = 0, j = ex.getRecordCount(); i < j; i++) {
final int ii = i;
if (ex.getRecordContext(i).hasErrors()) {
ex.getRecordContext(i).getFieldErrors().keySet().stream().forEach(key -> {
rejects.append("n");
rejects.append(ex.getRecordContext(ii).getLineNumber() + " : ");
rejects.append(ex.getRecordContext(ii).getRecordText() + " Field(" + key + ") : Error "
+ ex.getRecordContext(ii).getFieldErrors(key));

});
rejects.append("n");
}
}
}
});
Object record = null;
List<Person> persons = new ArrayList<Person>();
while ((record = reader.read()) != null) {
if ("header".equals(reader.getRecordName())) {
@SuppressWarnings("unchecked")
Map<String, Object> header = (Map<String, Object>) record;
System.out.println(header.get("fileDate"));
} else if ("detail".equals(reader.getRecordName())) {
Person person = (Person) record;
persons.add(person);
}
}
System.out.println(persons);
System.out.println("Errors:");
System.out.println(rejects);
}

您需要在salary字段中包含required="true"属性。

<field name="salary" minLength="1" required="true" />

然后,这将根据需要定义字段,并且字段的最小长度为1。这将给你所需的行为。

如果未将required设置为true,则该字段将被视为可选字段。即使字段可能是可选的,但当字段存在时,它仍然可能具有最小长度要求。

使用required和minLength的不同组合,您将了解BeanIO如何处理这些值,例如尝试

<field name="salary" minLength="1"/>
<field name="salary" minLength="1" required="true" />
<field name="salary" minLength="5"/>
<field name="salary" minLength="5" required="true" />

这个输入:

John|Smith|300000.00|34
Peter|William|800000.00|
Gregory|Rocky||30
John|Doe|1|30
Jane|Doe|100.00|30

参考指南对字段上所需的属性有以下说明:

如果需要此字段,请设置为true。如果需要字段,并且字段文本为空,BeanReader将抛出InvalidRecordException读取记录时。默认为false。

将年龄属性更改为required="false"或将其删除。

<record name="detail" minOccurs="0" maxOccurs="unbounded" class="com.test.Person">
<field name="firstName"/>
<field name="surname"/>
<field name="salary" minLength="1"/>        
<field name="age"/>
</record>

相关内容

  • 没有找到相关文章

最新更新