0

My question is how to convert the Integer value 0 to null? Previously I used the Xmappr annotation and it worked good with this annotation:

@Text 

Now I have to use BeanIO, so I tried:

@Field(xmlType=XmlType.Text) 

and it's not working.

The unit test needs to read number from XML file to be succesfull. If the personNumber from XML equals 0, it has to be written in the array as a null. In that case, the array should looks like this: [1,2,null].

XML file:

<Person ...> 1 </Person>
.
.
<Person ...> 2 </Person>
.
.
<Person ...> 0 </Person>

Annotation in Java previously:

@Text
private Integer personNumber;

Annotation in Java now:

@Field(xmlType=XmlType.Text)
private Integer personNumber;

Could it be the thing that I have to specify the format in the field annotation:

@Field(xmlType=XmlType.Text, format=....)
private Integer personNumber;

If so, what format should be specify?

Ensz
  • 75
  • 4
  • Have you tried setting nillable to true? http://beanio.org/2.1/docs/api/org/beanio/annotation/Field.html#nillable-- – OH GOD SPIDERS Oct 17 '17 at 08:34
  • Is `0` really equivalent to `null`? If your XML should _not_ contain a person number then why isn't the `` tag's body empty? – Thomas Oct 17 '17 at 08:37
  • @OHGODSPIDERS I tried, I got an error: xmLType 'text' is not nillable – Ensz Oct 17 '17 at 08:48
  • @Thomas The XML has to be the same as it was previously when there was xmappr annotations, can't really do anything with this. This part with is just small part of it :/ – Ensz Oct 17 '17 at 08:49
  • I'm not familiar with bean-io but I'd assume it can call setters if they are present. In that case you could handle 0 there. Alternatively, if you want to use a format (although I'm not sure what would happen on a violation) you'd probably need a regex, which then would be something like `^[1-9][0-9]*$`, i.e. a number starting with a digit greater than 0 and followed by any number of digits (inlcuding 0). – Thomas Oct 17 '17 at 09:24

1 Answers1

1

You can try to use a custom org.beanio.types.IntegerTypeHandler to return null when the number is '0'. Something like this:

import org.beanio.types.IntegerTypeHandler;

public class IntegerToNullTypeHandler extends IntegerTypeHandler {

  /**
   * {@inheritDoc}
   * @see org.beanio.types.IntegerTypeHandler#createNumber(java.lang.String)
   */
  @Override
  protected Integer createNumber(String text) throws NumberFormatException {
    if (text != null && "0".equals(text)) {
      return null;
    }
    return super.createNumber(text);
  }
}

To use this TypeHandler change the field on which you want to use the TypeHandler to:

@Field(xmlType=XmlType.Text, handlerClass=IntegerToNullTypeHandler.class)
private Integer personNumber;

I haven't tested this, but it should work.

nicoschl
  • 2,346
  • 1
  • 17
  • 17