编组错误:javax.xml.bind.JAXBException:类或其任何超类都知道此上下文

问题描述 投票:0回答:2

当我编组一个对象时,我得到了这个异常: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;
}
java jaxb marshalling unmarshalling xmlbeans
2个回答
1
投票

您需要在JAXBContext.newInstance实例化中指定上下文(也称为包名称)名称。它将找到位于该包装中的ObjectFactory.class,如文件中所示(第1页)

JAXBException - 如果在创建JAXBContext时遇到错误,例如

  1. 无法在包中找到ObjectFactory.class或jaxb.in​​dex
  2. contextPath中包含的全局元素之间的歧义
  3. 无法找到上下文工厂提供程序属性的值
  4. 在同一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;
}

0
投票

据我所知,有3种解决方案。

从xsd / wsdl中获取jaxb时会自动创建ObjectFactory类。

  1. 使用ObjectFactory方法创建必要的对象
marshaller.marshal(new com.myhealth.com.ObjectFactory().createSubscription(subscription), stringWriter);
  1. 在创建marshaller时直接使用类
JAXBContext.newInstance(Subscription.class).createMarshaller();
  1. 另一种已经在这里使用的方法。我的意思是通过ObjectFactory使用包名
JAXBContext.newInstance(com.myhealth.com.ObjectFactory.class
            .getPackage().getName()).createMarshaller();
© www.soinside.com 2019 - 2024. All rights reserved.