JAXB Marshalling Objects with java.lang.Object fie

2019-01-22 22:55发布

问题:

I'm trying to marshal an object that has an Object as one of its fields.

@XmlRootElement
public class TaskInstance implements Serializable {
   ...
   private Object dataObject;
   ...
}

The dataObject can be one of many different unknown types, so specifying each somewhere is not only impractical but impossible. When I try to marshal the object, it says the class is not known to the context.

MockProcessData mpd = new MockProcessData();
TaskInstance ti = new TaskInstance();
ti.setDataObject(mpd);

String ti_m = JAXBMarshall.marshall(ti);

"MockProcessData nor any of its super class is known to this context." is what I get.

Is there any way around this error?

回答1:

JAXB cannot marshal any old object, since it doesn't know how. For example, it wouldn't know what element name to use.

If you need to handle this sort of wildcard, the only solution is to wrap the objects in a JAXBElement object, which contains enough information for JAXB to marshal to XML.

Try something like:

QName elementName = new QName(...); // supply element name here
JAXBElement jaxbElement = new JAXBElement(elementName, mpd.getClass(), mpd);
ti.setDataObject(jaxbElement);


回答2:

Method:

public String marshallXML(Object object) {
        JAXBContext context;
        try {
            context = JAXBContext.newInstance(object.getClass());
            StringWriter writer = new StringWriter();
            Marshaller marshaller = context.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            marshaller.marshal(object, writer);
            String stringXML = writer.toString();
            return stringXML;
        } catch (JAXBException e) {

        }
}

Model:

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Customer {
    String name;
    int id;
    public String getName() {
        return name;
    }
    @XmlElement
    public void setName(String name) {
        this.name = name;
    }
    public int getId() {
        return id;
    }
    @XmlAttribute
    public void setId(int id) {
        this.id = id;
    }
}


标签: java jaxb