I have a given XML file that I want to parse on an Android device. Since an XmlPullParser has proven too cumbersome to maintain, I would prefer to use Jackson for easier deserialization. JAXB is not supported on Android devices as internal sun.* classes are missing, so it has to be Jackson, as far as I understand.
The main object (of type A) is a container for an arbitrary number of elements, each of which is an instance of a subclass of the abstract class B. All child elements of A are to be deserialized into a list of B objects.
This is the XML structure:
<A>
<B1/>
<B2/>
</A>
And my POJO class structure looks like this:
public class A { public List<B> list; }
public abstract class B {}
public class B1 extends B {}
public class B2 extends B {}
And this is my Parser code:
InputStream in = context.getResources().openRawResource(R.raw.my_xml_file);
A a = new XmlMapper().readValue(in, A.class));
Pretty straightforward. But how do I have to annotate these classes with Jackson?
There are a lot of examples out there how to do it in JSON, and I tried to use @JsonTypeInfo and @JsonSubTypes to give the name of the subclasses.
public class A {
@JsonTypeInfo(use=JsonTypeInfo.Id.NAME, include=JsonTypeInfo.As.PROPERTY, property="type")
@JsonSubTypes({
@JsonSubTypes.Type(name="B1", value=B1.class),
@JsonSubTypes.Type(name="B2", value=B2.class)
})
public List<B> list;
}
public abstract class B {}
public class B1 extends B { @XmlTransient public final String type="B1"; }
public class B2 extends B { @XmlTransient public final String type="B2"; }
But this uses a type property, which I do not have and do not want. I want the element name to be used as type information. If I use JsonTypeInfo.As.WRAPPER_OBJECT, it expects an additional XML element, so my XML would have to look like this:
<A>
<B><B1/></B>
<B><B2/></B>
</A>
What am I missing?