Exception on thread "main" javax.xml.bind.JAXBException: Provider com.sun.xml.bind.v2.ContextFactory could not be thrown
I am trying to test JAXB unmarshaller / marshaller. Here is my code
JAXBContext context = JAXBContext.newInstance(ClientUser.class.getPackage().getName());
And the code of my entity
@XmlRootElement(name = "user")
public class ClientUser {
private String name;
public ClientUser() {}
public ClientUser(String name) {
this.name = name;
}
@XmlElement(name = "name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Even if I add a factory class to the entity class
@XmlRegistry
class ObjectFactory {
ClientUser createPerson() {
return new ClientUser();
}
}
I am still getting this exception
Exception in thread "main" javax.xml.bind.JAXBException: Provider com.sun.xml.bind.v2.ContextFactory could not be instantiated: javax.xml.bind.JAXBException: "com.example.ws.poc.entity" doesnt contain ObjectFactory.class or jaxb.index
- with linked exception:
[javax.xml.bind.JAXBException: "com.example.ws.poc.entity" doesnt contain ObjectFactory.class or jaxb.index]
at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:146)
at javax.xml.bind.ContextFinder.find(ContextFinder.java:335)
at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:431)
at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:394)
at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:298)
How can I fix this error?
source to share
The JAXB implementation does not scan for packages. If you load the strap from a package name, JAXB will look for ObjectFactory
(annotated with @XmlRegistry
) or jaxb.index
file that contains short class names each on a new line.
If you don't have these two elements, you can create JAXBContext
on the domain classes themselves.
JAXBContext jc = JAXBContext.newInstance(Foo.class, Bar.class);
source to share
You can also get context from the type of class you want to deserialize. See below:
public class XmlDeserializer implements Deserializer {
public <T> T deserialize(String input, Class<T> outputType)
throws DeserializationException {
try {
JAXBContext jc = JAXBContext.newInstance(outputType);
Unmarshaller unmarshaller = jc.createUnmarshaller();
StringReader reader = new StringReader(input);
return outputType.cast(unmarshaller.unmarshal(reader));
} catch (JAXBException e) {
throw new DeserializationException(e.getMessage(), e);
}
}
}
source to share