0

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?

  • You need to tell Jackson what sub-types your class `B` has and how to name them. Jackson also needs to add a field where the actual class type is stored in. See this question how to add the correct annotations: https://stackoverflow.com/questions/29707933/fasterxml-jacksons-json-polymorphism-with-jsonsubtypes-and-jsontypeinfo – Robert May 28 '22 at 12:26
  • Thanks, but the field storing the class type is what I don't want! I cannot change the XML structure, as the document is given! – Kai Frerich May 28 '22 at 12:40
  • Then you need to write a custom deserializer for a basic deserializer see e.g. https://stackoverflow.com/a/50123297/150978 – Robert May 28 '22 at 13:30

0 Answers0