JAXB: Class B deserialization issue that extends class A

Please consider the following example:

There is ClassA and ClassB that extends it. My problem is that I need to undo the ClassB token from the xml file. Please note that ClassA cannot be changed since it is not under my control.

There are several problems noted in this example:

The main problem is that ClassA does not have a default no-arg constructor, which is required by JAXB without an adapter. So I implemented MyAdapter , which maps ClassB to a simple ValB class that can be handled by JAXB without problems.

The main problem is how to get JAXB to use this adapter? Neither the definition of @XmlJavaTypeAdapter at the class level, nor the registration of the adapter for a non-marshaller do.

Does anyone know how to get JAXB to use MyAdapter so that unmarshaller returns an object that is an instance of ClassA ?

public class JaxbTest { public static abstract class ClassA { public ClassA(String id) { } } @XmlRootElement @XmlJavaTypeAdapter(MyAdapter.class) // does not have an effect public static class ClassB extends ClassA { public String text; public ClassB() { super(""); } } public static class ValB { public String text; } public static class MyAdapter extends XmlAdapter<ValB, ClassB> { @Override public ClassB unmarshal(ValB v) throws Exception { ClassB b = new ClassB(); b.text = v.text; return b; } @Override public ValB marshal(ClassB v) throws Exception { ValB b = new ValB(); b.text = v.text; return b; } } public static void main(String[] args) { try { JAXBContext context = JAXBContext.newInstance(ClassB.class); Unmarshaller unmarshaller = context.createUnmarshaller(); unmarshaller.setAdapter(new MyAdapter()); // does not have an effect ClassA a = (ClassA) unmarshaller.unmarshal(new File("test.xml")); // do somthing with a } catch (Exception e) { e.printStackTrace(); } } } 

BTW: Don't take the code too seriously - this is just an example that demonstrates the problem. I know that defining ClassA and ClassB is not very useful.

+6
java constructor adapter jaxb unmarshalling
source share
1 answer

UPDATE

We addressed this issue in the upcoming release of EclipseLink JAXB (MOXy) 2.2.0 (see bug # 332742 ). In this release, abstract classes will not be checked for the no-arg constructor.

Preliminary versions with this fix can be obtained here starting December 18:

Bypass

This is the @XmlTransient annotation. If possible, follow these steps:

 @XmlTransient public static abstract class ClassA { public ClassA(String id) { } } 

If you cannot annotate ClassA directly, you can use the EclipseLink JAXB (MOXy) extension to do this. MOXy allows you to specify JAXB metadata as an XML file. This is useful if you cannot change the model class:

Below are some articles explaining @XmlAdapter:

+2
source share

All Articles