javax.xml.bind.JAXBException: Class *** nor any of its super class is known to this context
JAX-RS implementations automatically support marshalling/unmarshalling of classes based on discoverable JAXB annotations, but because your payload is declared as Object
, I think the created JAXBContext
misses the Department
class and when it's time to marshall it it doesn't know how.
A quick and dirty fix would be to add a XmlSeeAlso
annotation to your response class:
@XmlRootElement
@XmlSeeAlso({Department.class})
public class Response implements Serializable {
....
or something a little more complicated would be "to enrich" the JAXB context for the Response
class by using a ContextResolver
:
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.Provider;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
@Provider
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public class ResponseResolver implements ContextResolver<JAXBContext> {
private JAXBContext ctx;
public ResponseResolver() {
try {
this.ctx = JAXBContext.newInstance(
Response.class,
Department.class
);
} catch (JAXBException ex) {
throw new RuntimeException(ex);
}
}
public JAXBContext getContext(Class<?> type) {
return (type.equals(Response.class) ? ctx : null);
}
}
I have the same problem and I solved it by adding package to explore to the Jaxb2marshaller. For spring will be define a bean like this:
@Bean
public Jaxb2Marshaller marshaller() {
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
String[] packagesToScan= {"<packcge which contain the department class>"};
marshaller.setPackagesToScan(packagesToScan);
return marshaller;
}
By this way if all your request and response classes are in the same package you do not need to specifically indicate the classes on the JAXBcontext
This exception can be solved by specifying a full class path.
Example:
If you are using a class named ExceptionDetails
Wrong Way of passing arguments
JAXBContext jaxbContext = JAXBContext.newInstance(ExceptionDetails.class);
Right Way of passing arguments
JAXBContext jaxbContext = JAXBContext.newInstance(com.tibco.schemas.exception.ExceptionDetails.class);