带有注释的beanIO-将对象列表写入json文件

时间:2018-07-31 18:07:06

标签: java json file-writing fileparsing bean-io

我必须使用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文件。

谢谢..

1 个答案:

答案 0 :(得分:0)

问题在于Department类的配置。 maxOccursSegment属性的默认值为Integer.MIN_VALUE,因此,如果要使用映射文件,则需要将其设置为“ unbounded”,但可以将其设置为-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
}

在使用注释并且需要按特定顺序输出字段时,请注意注释文档的part

  

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