4spir
4spir

Reputation: 1184

JAXB Marshall String to base64

I need to marshall an object which includes a String variable.
The String var. contains an XML document, and it gets marshalled with escaping to XMLElement.

I'd like to marshall the String variable to base64 format, and back to String on unmarshall.

Is this posiible?

Upvotes: 2

Views: 8149

Answers (1)

bdoughan
bdoughan

Reputation: 149037

You can use an XmlAdapter to convert the String to/from a byte[] during the marshalling/unmarshalling process. By default JAXB will represent a byte[] as base64Binary.

XmlAdapter (Base64Adapter)

Below is an XmlAdapter that will convert between a String and a byte[].

import javax.xml.bind.annotation.adapters.XmlAdapter;

public class Base64Adapter extends XmlAdapter<byte[], String> {

    @Override
    public String unmarshal(byte[] v) throws Exception {
        return new String(v);
    }

    @Override
    public byte[] marshal(String v) throws Exception {
        return v.getBytes();
    }

}

Java Model (Foo)

The XmlAdapter is configured using the @XmlJavaTypeAdapter annotation.

import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;

@XmlRootElement
public class Foo {

    private String bar;

    @XmlJavaTypeAdapter(Base64Adapter.class)
    public String getBar() {
        return bar;
    }

    public void setBar(String bar) {
        this.bar = bar;
    }

}

Demo

In the demo code below we will create an instance of Foo and marshal it to XML.

import javax.xml.bind.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Foo.class);

        Foo foo = new Foo();
        foo.setBar("<abc>Hello World</abc>");

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(foo, System.out);
    }

}

Output

Below is the output from running the demo code:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<foo>
    <bar>PGFiYz5IZWxsbyBXb3JsZDwvYWJjPg==</bar>
</foo>

Upvotes: 8

Related Questions