JAXB使用java.lang.Object字段编组对象 [英] JAXB Marshalling Objects with java.lang.Object field

查看:255
本文介绍了JAXB使用java.lang.Object字段编组对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试封送一个将Object作为其字段之一的对象。

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

dataObject可以是众多不同的 unknown 类型,因此指定每个地方不仅不切实际,而且不可能。当我试图封送该对象时,它表示该类不为上下文所知。

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及其任何超级类都是已知的。就是我得到的。

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

有没有办法绕过这个错误?

Is there any way around this error?

推荐答案

JAXB不能编组任何旧对象,因为它不知道如何。例如,它不知道要使用的元素名称。

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

如果需要处理这种通配符,唯一的解决方案是将对象包装在 JAXBElement object,其中包含足以让JAXB编组为XML的信息。

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.

尝试类似:

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

这篇关于JAXB使用java.lang.Object字段编组对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆