简体   繁体   English

带有 java.lang.Object 字段的 JAXB 编组对象

[英]JAXB Marshalling Objects with java.lang.Object field

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. dataObject 可以是许多不同的未知类型之一,因此在某处指定每个类型不仅不切实际而且不可能。 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." “MockProcessData 或其任何超类在此上下文中都是已知的。” is what I get.是我得到的。

Is there any way around this error?有没有办法解决这个错误?

JAXB cannot marshal any old object, since it doesn't know how. JAXB 无法编组任何旧对象,因为它不知道如何编组。 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.如果您需要处理此类通配符,唯一的解决方案是将对象包装在JAXBElement对象中,该对象包含足够的信息供 JAXB 编组为 XML。

Try something like:尝试类似:

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

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;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM