JAXB (un)marshalling of xsd types: xsd:base64Binary and xsd:hexBinary

萝らか妹 提交于 2019-12-03 15:57:26

The conversion between byte[] and the hexBinary or base64Binary representation is done via a correspondent XmlAdapter.

by default JAXB uses the included HexBinaryAdapter for converting byte[] to a String. I don't know if there is also an XmlAdapter which converts from/to base64 but that is no problem:

You can easily implement it yourself using an own XmlAdpater:

public final class Base64Adapter extends XmlAdapter<String, byte[]> {
    public byte[] unmarshal(String s) {
        if (s == null)
            return null;
        return org.apache.commons.codec.binary.Base64.decodeBase64(s);
    }

    public String marshal(byte[] bytes) {
        if (bytes == null)
            return null;
        return org.apache.commons.codec.binary.Base64.encodeBase64String(bytes);
    }
}

You can specify on a field/getter_setter level what should be processed by which adapter:

private class DataTestClass {

    @XmlJavaTypeAdapter(Base64Adapter.class)
    public byte[] base64Data = new byte[] { 0, 1, 2, 3, 4 };

    @XmlJavaTypeAdapter(HexBinaryAdapter.class)
    public byte[] hexbinData = new byte[] { 0, 1, 2, 3, 4 };

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!