Hey guys.
Got a quick question. Does anyone know how to let JAXB (marshall) render boolean fields as 1 and 0 instead of printing out "true" and "false"?
Hey guys.
Got a quick question. Does anyone know how to let JAXB (marshall) render boolean fields as 1 and 0 instead of printing out "true" and "false"?
You can write a pair of parser/writers and define the property mapping in binding JAXB XML.
I would probably create a type adapter for converting a boolean to an int. There are some examples in the JAXB users guide.
JAXB provides a flexible way to customize your bindings. You simply have to write an XML file that will indicate how you want to bind your XML and Java types. In your case, you could use a <javaType>
declaration, in which you can specify a parseMethod
and a printMethod
. These methods could be as simple as
public boolean myParseBool(String s)
{
return s.equals("1");
}
public String myPrintBool(boolean b)
{
return b ? "1" : "0";
}
There might exist easier ways, maybe using DatatypeConverter, but I'm not enough aware of this subject to help you more !
The adaptor class:
import javax.xml.bind.annotation.adapters.XmlAdapter;
public class BooleanAdapter extends XmlAdapter<Integer, Boolean>
{
@Override
public Boolean unmarshal( Integer s )
{
return s == null ? null : s == 1;
}
@Override
public Integer marshal( Boolean c )
{
return c == null ? null : c ? 1 : 0;
}
}
Usage:
@XmlElement( name = "enabled" )
@XmlJavaTypeAdapter( BooleanAdapter.class )
public Boolean getEnabled()
{
return enabled;
}