0

我有一个简单的类,它必须是marshalled/unmarshalled具有特定的XmlAdapter

package jaxb;

import java.io.Serializable;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.Arrays;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;

import org.eclipse.persistence.jaxb.JAXBContextFactory;
import org.xml.sax.InputSource;

@XmlRootElement(name = "simpleClass")
@XmlAccessorType(XmlAccessType.FIELD)
@XmlJavaTypeAdapter(MyAdapter.class)
public class SimpleClass implements Serializable {

    private static final long serialVersionUID = 1L;

    public byte[] bytes;

    /**
     * Return bytes value or reference.
     *
     * @return bytes value or reference.
     */
    public byte[] getBytes() {
        return bytes;
    }

    /**
     * Set bytes value or reference.
     *
     * @param bytes Value to set.
     */
    public void setBytes(byte[] bytes) {
        this.bytes = bytes;
    }

    public static void main(String[] args) {

        try {

            JAXBContext context = JAXBContextFactory.createContext(new Class[] {
                    SimpleClass.class
            }, null);
            Unmarshaller unmarshaller = context.createUnmarshaller();
            Marshaller marshaller = context.createMarshaller();

            StringWriter sw = new StringWriter();
            StringReader sr = new StringReader("<simpleClass><bytes>DT8d6/Y8/Ig=</bytes></simpleClass>");

            SimpleClass binaryData = (SimpleClass) unmarshaller.unmarshal(new InputSource(sr));
            System.out.println("Unmarshal is: " + binaryData + "");
            System.out.println("Binary data bytes: " + Arrays.toString(binaryData.bytes) + " ");

            marshaller.marshal(binaryData, sw);
            System.out.println("Marshal is: " + sw.toString() + "");

        }

        catch (Throwable e) {

            e.printStackTrace();
        } finally {

        }
    }
}

我的适配器如下:

package jaxb;

public class MyAdapter extends XmlAdapter<String, Object> {

    @Override
    public String marshal(Object arg0) throws Exception {

        ...
    }

    @Override
    public Object unmarshal(String arg0) throws Exception {
        ...
    }
}

我认为这足以告诉JAXB引擎使用提供的适配器类来编组/解组 SimpleClass 对象。看起来适配器没有在@XmlRootElement对象上调用,而只是在它的字段上调用。实际上,如果我XmlJavaTypeAdapter在字段上使用注解"bytes",例如调用适配器。

任何帮助将不胜感激。

4

0 回答 0