0

我必须使用 beanIO 将对象列表写入 json 文件。每当我尝试时,我只会得到第一个被写入文件的对象,如下所示。

{"employeeDetails":[{"recordType":"I","empId":"100","empName":"Name1"}]}

实际结果应该如下:

{"employeeDetails":[{"recordType":"I","empId":"100","empName":"Name1"},{"recordType":"I","empId":"101","empName":"Name2"}]}

使用 pojo 如下:

@Record
public class Employee{

@Field(minOccurs=0)
private String recordType;
@Field(minOccurs=0)
private String empId;
@Field(minOccurs=0)
private String empName;

// getters and setters
}

@Record
public class Department{

@Segment(minOccurs=0, collection=List.class)
private List<Employee> employeeDetails;

//getters and setters
}

这就是我的 impl 类所做的,

StreamFactory streamFactory=StreamFactory.newInstance(); 
streamFactory.loadResource(beanIoPath + beanIoMappingFileName); 
Writer outJson = new BufferedWriter(new FileWriter(new File(absPath+fileName))); 
BeanWriter jsonBeanWriter = streamFactory.createWriter(mapper, outJson); 
Department dpt = //fetch from db; 
jsonBeanWriter.write(dpt);

请建议应该添加什么,如何使用 BeanIO 实现将对象列表写入 json 文件。

谢谢..

4

1 回答 1

0

问题在于Department类的配置。maxOccursa 上属性的默认值为SegmentInteger.MIN_VALUE因此如果要使用映射文件,则需要将其设置为“无界”,但-1在使用注释时可以将值设置为。从@Segment注释的源代码:

/**
 * The maximum occurrences.
 * @return the maximum occurrences, or -1 if unbounded
 */
int maxOccurs() default Integer.MIN_VALUE;

然后,您的Department课程需要如下所示:

@Record
public class Department {

  @Segment(minOccurs = 0, maxOccurs = -1, collection = List.class)
  private List<Employee> employeeDetails;

//getters and setters
}

当您使用注释并需要按特定顺序输出字段时,请注意注释文档的这一部分:

使用注解时,强烈建议显式设置所有字段和段的位置(使用 at)。BeanIO 不保证将带注释的组件添加到布局中的顺序。

于 2018-08-01T09:55:19.680 回答