How to let JAXB render boolean as 0 and 1, not true and false

前端 未结 5 1612
死守一世寂寞
死守一世寂寞 2020-12-08 19:53

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

5条回答
  •  抹茶落季
    2020-12-08 20:26

    The adapter class:

    import javax.xml.bind.annotation.adapters.XmlAdapter;
    
    public class BooleanAdapter extends XmlAdapter
    {
        @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;
    }
    

提交回复
热议问题