带有 java.lang.Object 字段的 JAXB 编组对象 [英] JAXB Marshalling Objects with java.lang.Object field

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

问题描述

我正在尝试将一个对象作为其字段之一编组.

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 可以是许多不同的未知类型之一,因此在某处指定每个类型不仅不切实际而且不可能.当我尝试封送对象时,它说上下文不知道该类.

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 对象中,该对象包含足够的信息供 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);

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

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