I'm trying to unmarshal xml file which have some optional attributes (the attribute can be included in an element, but sometimes it's missing). How can I create an optional java objects from those attributes?
XML:
...
<example a="s"
     b="2.0"
/>
<example a="z"
/>
...
Java:
@XmlRootElement(name = "example")
public class ExampleDTO {
  private String a;
  private Optional<Float> b;
  public String getA() {
    return a;
  }
  @XmlAttribute
  public void setA(String a) {
    this.a = a;
  }
  public Optional<Float> getB() {
    return b;
  }
  @XmlAttribute
  @XmlJavaTypeAdapter(FloatOptionalAdapter.class)
  public void setB(Optional<Float> b) {
    this.b= b;
  }
Adapter:
public class FloatOptionalAdapter extends XmlAdapter<Float, Optional<Float>> {
  @Override
  public Optional<Float> unmarshal(Float v) throws Exception {
    return Optional.ofNullable(v);
  }
  @Override
  public Float marshal(Optional<Float> v) throws Exception {
    if (v == null || !v.isPresent()) {
      return null;
    } else {
      return v.get();
    }
  }
}
When I run this code I get 2 objects of ExampleDTO. In the first one, I get Optional object with "2.0" value. In the second one, the value of b is "null". How can I make the value to be an empty Optional object?
 
    