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

前端 未结 5 1617
死守一世寂寞
死守一世寂寞 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:43

    Having the same problem as user20298, I followed the hint by mtpettyp, and adapted it for my configuration.

    My configuration is: - maven to build the project. - "org.jvnet.jaxb2.maven2" plugin in maven. - jaxb 2.2.6 - In this occasion, I was making Java classes for the kml 2.2 (ogckml22.xsd)

    And I stumbled upon the problem of the booleans to be rendered as 'true/false', when Google maps wants them to be as '1/0'

    This is the plugin configuration in maven:

    
    org.jvnet.jaxb2.maven2
    maven-jaxb2-plugin
    
        
            generate-sources
            
                generate
            
        
    
    
        src/main/generated
        true
        true
    
    

    I added to the src/main/resources folder a jaxb-bindings.xjb file with the following content:

        
    
        
            
            
        
        ...
        ...
    
    

    The adapter class is like:

    package path.to.my;
    
    import javax.xml.bind.annotation.adapters.XmlAdapter;
    
    /**
     * Utility class to correctly render the xml types used in JAXB.
     */
    public class JaxbBooleanAdapter extends XmlAdapter
    {
        @Override
        public Boolean unmarshal(String v) throws Exception
        {
            if ("1".equals(v))
            {
                return true;
            }
            return false;
        }
    
        @Override
        public String marshal(Boolean v) throws Exception
        {
            if (v == null)
            {
                return null;
            }
            if (v)
            {
                return "1";
            }
            return "0";
        }
    }
    

提交回复
热议问题