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

App*_*pps 5 java web-services jaxb

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

<xs:complexType name="payload">
    <xs:sequence>
        <xs:any processContents="lax"></xs:any>
    </xs:sequence>
</xs:complexType>
Run Code Online (Sandbox Code Playgroud)

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

 @XmlAnyElement(lax = true)
 private Object any;
Run Code Online (Sandbox Code Playgroud)

以下是我JAXB生成的WebServiceRequestVO 的结构.

@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;
}
Run Code Online (Sandbox Code Playgroud)

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

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class AddressVO {
    @XmlElement
    private String pinCode;
    @XmlElement
    private String city;
}
Run Code Online (Sandbox Code Playgroud)

我填充了此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.
Run Code Online (Sandbox Code Playgroud)

你能否提出一些方法来克服这个问题?在一个链接中提到包括@XmlSeeAlso,但我不能这样做,因为我的有效载荷是非常通用的.请在这方面帮助我.

My-*_*-Is 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);
        }
    }
} 
Run Code Online (Sandbox Code Playgroud)

和类型的concreate实现 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

你现在需要的是一个简洁的修改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);
    }
}
Run Code Online (Sandbox Code Playgroud)

使用此方法,您可以通过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);
        ...
    }
    ...
}
Run Code Online (Sandbox Code Playgroud)