tags:

views:

1279

answers:

5

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"?

A: 

You can write a pair of parser/writers and define the property mapping in binding JAXB XML.

Dennis Cheung
A: 

Got any example or link to that?

+1  A: 

I would probably create a type adapter for converting a boolean to an int. There are some examples in the JAXB users guide.

Guðmundur Bjarni
+3  A: 

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 !

Luc Touraille
+3  A: 

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;
}
mtpettyp
Excellent! Just what I needed!
Nils Weinander