javajsonfile-writingfileparsingbean-io

beanIO with annotations - writing list of objects to a json file


I have to write a list of obects to a json file using beanIO. whenever i tried i am getting only the first object getting written to the file as below.

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

actual result should be as below:

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

using pojo as below:

@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
}

this is what my impl class does,

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);

Please suggest what should be added more, how to achieve writing list of objects into a json file using BeanIO.

Thank you..


Solution

  • The problem is with the configuration of the Department class. The default value for the maxOccurs attribute on a Segment is Integer.MIN_VALUE, so you need to make it "unbounded" if you were to use the mapping file, but you can set the value to -1 when using annotations. From the source code for the @Segment annotation:

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

    Your Department class then needs to look like this:

    @Record
    public class Department {
    
      @Segment(minOccurs = 0, maxOccurs = -1, collection = List.class)
      private List<Employee> employeeDetails;
    
    //getters and setters
    }
    

    When you are using annotations and need the output of your fields in a specific order, take note of this part of the documentation on annotations:

    When using annotations, it is strongly recommended to explicitly set the position (using at) for all fields and segments. BeanIO does not guarrantee the order in which annotated components are added to a layout.