javax.xml.bind.MarshalException - 带有链接异常:[javax.xml.bind.JAXBException:类**或其任何超类都知道此上下文

时间:2013-12-19 16:07:58

标签: java web-services jaxb

我有一个期望WebServiceRequest对象的通用Web服务。此对象具有Object类型的有效内容。以下是我的有效载荷的类型。

<xs:complexType name="payload">
    <xs:sequence>
        <xs:any processContents="lax"></xs:any>
    </xs:sequence>
</xs:complexType>

我为Web服务输入和输出类型创建了JAXB个类。所以对于有效载荷,这是生成的字段。

 @XmlAnyElement(lax = true)
 private Object any;

以下是我JAXB生成WebServiceRequest VO的结构。

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "serviceRequest", namespace = "http://ws.test.svc.com/", propOrder = {
    "payload"
})
public class WebServiceRequest{
        @XmlElement
        private Payload payload;
} 

public class Payload{
 @XmlAnyElement(lax = true)
 private Object any;
}

我有一些自定义POJO,我需要填充并设置为有效负载。我使用以下注释

注释了这些POJO
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class AddressVO {
    @XmlElement
    private String pinCode;
    @XmlElement
    private String city;
}

我填充了此POJO的数据,并尝试将其设置为WebServiceRequest的有效负载。但是当我这样做时,我得到了以下异常。

javax.xml.bind.MarshalException
 - with linked exception:
[javax.xml.bind.JAXBException: class com.vo.test.AddressVO nor any of its super class is known to this context.

你能否提出一些解决方法?在一个link中,提到包括@XmlSeeAlso,但我不能这样做,因为我的有效载荷非常通用。在这方面请帮助我。

1 个答案:

答案 0 :(得分:5)

如果您无法应用@XMLSeeAlso注释,则需要创建自定义MessageBodyReaderMessageBodyWriter,它们负责在java和XML之间编组和解组。下面显示了一个通用MessageBodyReader的抽象实现,它实际上是为了进行类型特定的XML验证。作者非常相似,因此没有添加。

public abstract class AbstractXmlValidationReader<T> implements
        MessageBodyReader<T> {

    private final Providers providers;
    private final Schema schema;

    public AbstractXmlValidationReader(final Providers providers,
            final ServletContext servletContext, final String xsdFileName) {
        this.providers = providers;

        try {
            SchemaFactory sf = SchemaFactory
                    .newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            File xsd = new File(servletContext.getRealPath(xsdFileName));
            schema = sf.newSchema(xsd);
        } catch (Exception e) {
            throw new RuntimeException(
                    "Unable to create XSD validation schema", e);
        }
    }

    @Override
    public boolean isReadable(Class<?> type, Type genericType,
            Annotation[] annotations, MediaType mediaType) {

        @SuppressWarnings("unchecked")
        Class<T> readableClass = (Class<T>) ((ParameterizedType) getClass()
                .getGenericSuperclass()).getActualTypeArguments()[0];

        if (type == readableClass
                && type.isAnnotationPresent(XmlRootElement.class)) {
            return true;
        }
        return false;
    }

    @Override
    public T readFrom(Class<T> type, Type genericType,
            Annotation[] annotations, MediaType mediaType,
            MultivaluedMap<String, String> httpHeaders, InputStream entityStream)
            throws IOException, WebApplicationException {

        try {
            JAXBContext jaxbContext = null;
            ContextResolver<JAXBContext> resolver = providers
                    .getContextResolver(JAXBContext.class, mediaType);
            if (null != resolver) {
                jaxbContext = resolver.getContext(type);
            }
            if (null == jaxbContext) {
                jaxbContext = JAXBContext.newInstance(type);
            }
            Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
            unmarshaller.setSchema(schema);

            @SuppressWarnings("unchecked")
            T entity = (T) unmarshaller.unmarshal(entityStream);
            return entity;
        } catch (JAXBException e) {
            throw new MessageBodyReaderValidationException(
                    "Failure while performing xml validation or xml marhalling!",
                    e);
        }
    }
} 

类型Address

的混合实现
@Provider
@Consumes(MediaType.APPLICATION_XML)
public class AddressXmlValidationReader extends
        AbstractXmlValidationReader<Address> {

    private final static String xsdFileName = "/xsd/Address.xsd";

    public AddressXmlValidationReader(@Context Providers providers,
            @Context ServletContext servletContext) {
        super(providers, servletContext, xsdFileName);
    }
}

您现在需要的是readFrom的一种简洁的MessageBodyReader方法,可能如下所示。对于MessageBodyWriter,该方法称为writeTo

@Override
public T readFrom(Class<T> type, Type genericType,
        Annotation[] annotations, MediaType mediaType,
        MultivaluedMap<String, String> httpHeaders, InputStream entityStream)
        throws IOException, WebApplicationException {

    try {
        JAXBContext jaxbContext = null;
        ContextResolver<JAXBContext> resolver = providers
                .getContextResolver(JAXBContext.class, mediaType);

        if(entityStream != null){
            // TODO read the entityStream and determine the concrete type of the XML content
            type = ... ;
        }

        if (null != resolver) {
            jaxbContext = resolver.getContext(type);
        }
        if (null == jaxbContext) {
            jaxbContext = JAXBContext.newInstance(type);
        }
        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        unmarshaller.setSchema(schema);

        @SuppressWarnings("unchecked")
        T entity = (T) unmarshaller.unmarshal(entityStream);
        return entity;
    } catch (JAXBException e) {
        throw new MessageBodyReaderValidationException(
                "Failure while performing xml validation or xml marhalling!",
                e);
    }
}

使用此方法,您可以通过Reader和Writer实例的具体子类定义一般类型。一个可能更具体的类型可以在抽象基类中确定(比如在这个例子中),也可以从其他地方注入。当然,您可以修改此MessageBodyReader,以便XML输入的具体类型可以在某处或其他地方确定。但总的来说,这就是解决问题的方法。


注意:

不要忘记在Web服务Application类中注册具体的Reader和writer实现。

@ApplicationPath("/services")
public class WSApplication extends Application {
    private Set<Object> singletons = new HashSet<Object>();
    private Set<Class<?>> classes = new HashSet<Class<?>>();
    public WSApplication() {
        ...
        classes.add(AddressXmlValidationReader.class);
        ...
    }
    ...
}