Representing an element as Boolean with JAXB?

We have this XML:

  <Summary>
     <ValueA>xxx</ValueA>
     <ValueB/>
  </Summary>

<ValueB/>will never have any attributes or internal elements. This is an element of type boolean - it exists (true) or does not matter (false).

JAXB generated a Summary class with a String valueA element, which is good. But for ValueB, JAXB created an inner ValueB class and the corresponding member:

@XmlElement(name = "ValueB")
protected Summary.ValueB valueB;

But I need a member booleanand not an inner class:

@XmlElement(name = "ValueB")
protected boolean valueB;

How can you do this?

I do not want to restore classes, I would just like to change the code manually.


Update . In accordance with the accepted answer, we created a new method that returns a logical value, depending on the value valueB == null.

Hibernate, B @Transient Hibernate @Column.

+2
2

jaxb , , commplexAttribute

, , null == valueB,

@XmlElement(name = "ValueB", nillable='true') protected Summary.ValueB valueB; .

getter, @XMl.... valueB , , , JAXB, .

+1

XmlAdaptor:

package com.example.xml.adaptor;
import javax.xml.bind.annotation.adapters.XmlAdapter;

public class BooleanToEmptyObjectAdapter extends XmlAdapter<EmptyObject, Boolean> {
    @Override
    public EmptyObject marshal(final Boolean v) {
        return v != null && v ? new EmptyObject() : null;
    }

    @Override
    public Boolean unmarshal(final EmptyObject v) {
        return true;
    }
}

:

package com.example.xml.adaptor;

public class EmptyObject {
    // EMPTY
}

Boolean ( a Boolean):

@XmlRootElement(name = "FooElement")
public class Foo {

    @XmlElement()
    @XmlJavaTypeAdapter(BooleanToEmptyObjectAdapter.class)
    private final Boolean isPresent = false;

    ...
    // You might need to @XmlTransient your getter/setter, or JAXB might complain about redefinition
    @XmlTransient
    public boolean isPresent() {
        return this.isPresent;
    }
}

<isPresent/>, true, , false.

+6

All Articles