5
votes

I am trying to use byte array like this (JAXB class). However, I am getting all 0s in the msg field even though I pass valid characters. The "id" and "myid" fields are parsed successfully and it is failing for the byte array field.

@XmlRootElement(name = "testMessage")
@XmlAccessorType(XmlAccessType.FIELD)
public class TestMessage
{
    @XmlAttribute
    private Integer id;

    @XmlElement(name = "myid")
    private Long myid;

    @XmlElement(name = "msg")
    private byte[] msg;
}
2
What is the XML Schema Data Type of the msg element (It should probably be hex or base 64 binary?jabbie

2 Answers

4
votes

Using JAXB of Java 1.6.0_23 i get the following xml file for a TestMessage instance:

TestMessage testMessage = new TestMessage();
testMessage.id = 1;
testMessage.myid = 2l;
testMessage.msg = "Test12345678".getBytes();

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<testMessage id="1">
    <myid>2</myid>
    <msg>VGVzdDEyMzQ1Njc4</msg>
</testMessage>

If you unmarshall this xml content you should get back the TestMessage instance including the msg byte array (which is base64 encoded in the xml file).

0
votes
  • You can use xml adapters for your byte array xml element. As you now, every element get marshalling/unmarshalling and adapters are use for situations such as converting date time with specified format, type convertions etc. while marshalling/unmarshalling.

  • HexBinaryAdapter class is one of those adapters belongs to javax.xml.bind.annotation.adapters so you can use it.

    public class TestMessage {
        @XmlAttribute
        private Integer id;
    
        @XmlElement(name = "myid")
        private Long myid;
    
        @XmlJavaTypeAdapter(HexBinaryAdapter.class)
        @XmlElement(name = "msg")
        private byte[] msg;
    }
    

Yet, if you prefer a custom convertion, you can create your own adapter for converting bytes for a specified format such as base64 etc.

To do that you must write your own unmarshalling/marshalling methods,

public final class MyAdapter extends XmlAdapter<String, byte[]> {
    public byte[] unmarshal(String s) {
        if (s == null)
            return null;
        return decode()); // your way to decode.
    }

    public String marshal(byte[] bytes) {
        if (bytes == null)
            return null;
        return encode(); //your way to encode
    }
}

then you give your marshaller/unmarshaller in @XmlJavaTypeAdapter anotation ;

    public class TestMessage {
        @XmlAttribute
        private Integer id;

        @XmlElement(name = "myid")
        private Long myid;

        @XmlJavaTypeAdapter(MyAdapter.class)
        @XmlElement(name = "msg")
        private byte[] msg;
    }