javabean-io

BeanIO default values for optional segments fields for XML input file?


I have a sample input XML with below structure:

<students>
    <student>
        <name>Peter</name>
        <intern>
            <internLocation>Ohio</internLocation>
        </intern>
    </student>
    <student>
        <name>John</name>       
    </student>
</students>

And beanio config:

<beanio xmlns="http://www.beanio.org/2012/03">
    <stream name="students" format="xml" strict="true">
        <record name="student" class="com.testapp.model.Student">
            <field name="studentName" xmlName="name" maxLength="20" />
            <segment name="intern" minOccurs="0">
                <field name="internLocation" maxLength="50" minOccurs="0" default="" />
            </segment>      
        </record>
    </stream>
</beanio>

And Model class:

public class Student {
private String studentName;
private String internLocation;
(...)

}

As you can see <intern> segment is optional. How can I default internLocation field of Student class to some value in case the segment is not present? I've tried annotating the field like below but still null value is coming:

@Field(defaultValue = "")
private String internLocation;

Solution

  • There are 2 ways to get the desired behaviour you are after.

    First, assign the default value, to the variable in the bean, without any annotation:

    private String internLocation = "";
    

    Secondly, which is basically the same thing, just done differently, is to handle the default value in the getter:

    public String getInternLocation() {
    
      return internLocation == null ? "" : internLocation;
    }
    

    I know, it would be nice to be able to do all of this in the mapping xml file.

    PS: Double check your mapping file posted above, it doesn't work with the given XML. The xmlName attribute is wrong for the internLocation field.