当我编组一个对象时,我得到了这个异常:javax.xml.bind.JAXBException:类Subscription或它的任何超类都是这个上下文已知的。
我知道@XmlSeeAlso有解决方案并修改jaxb类但是当我们从XSD / WSDL文件生成JAXB类时,我们无法更改它们。因此,这些解决方案不适用于此方案。
public static String getStringFromSubscription(Subscription subscription) throws MbException
{
Marshaller marshaller;
StringWriter stringWriter = new StringWriter();
try
{
marshaller = JAXBContext.newInstance(com.myhealth.com.ObjectFactory.class
.getPackage().getName()).createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
marshaller.setProperty("com.sun.xml.bind.xmlDeclaration", Boolean.FALSE);
marshaller.marshal(subscription, stringWriter);
}
catch (Exception e)
{
throw new MbException(e);
}
return stringWriter;
}
您需要在JAXBContext.newInstance
实例化中指定上下文(也称为包名称)名称。它将找到位于该包装中的ObjectFactory.class
,如文件中所示(第1页)
JAXBException - 如果在创建JAXBContext时遇到错误,例如
- 无法在包中找到ObjectFactory.class或jaxb.index
- contextPath中包含的全局元素之间的歧义
- 无法找到上下文工厂提供程序属性的值
- 在同一contextPath上混合来自不同提供者的模式派生包
public static String getStringFromSubscription(Subscription subscription) throws MbException {
Marshaller marshaller;
StringWriter stringWriter = new StringWriter();
try {
marshaller = JAXBContext.newInstance("com.myhealth.com").createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
marshaller.setProperty("com.sun.xml.bind.xmlDeclaration", Boolean.FALSE);
marshaller.marshal(subscription, stringWriter);
} catch (Exception e) {
throw new MbException(e);
}
return stringWriter;
}
据我所知,有3种解决方案。
从xsd / wsdl中获取jaxb时会自动创建ObjectFactory类。
marshaller.marshal(new com.myhealth.com.ObjectFactory().createSubscription(subscription), stringWriter);
JAXBContext.newInstance(Subscription.class).createMarshaller();
JAXBContext.newInstance(com.myhealth.com.ObjectFactory.class
.getPackage().getName()).createMarshaller();