Home > Software engineering >  Jackson-alternative to SimpleXML's @ElementListUnion
Jackson-alternative to SimpleXML's @ElementListUnion

Time:12-15

Serializing a list that may contain elements with different types in Java using SimpleXML, you can you something such as

class Root {
  @ElementListUnion({
    @ElementList(entry = "Foo", type = Foo.class, inline = true),
    @ElementList(entry = "Bar", type = Bar.class, inline = true)
  })
  protected List<Object> fooOrBar;
}

This will end up being serialized to

<Root>
  <Foo>
    {correct Foo serialization}
  </Foo>
  <Bar>
    {correct Bar serialization}
  </Bar>
</Root>

Is there any Jackson-alterantive to @ElementListUnion, or a workaround? I could create a custom serializer - how would I go about creating a custom serializer that will only alter the name based on type?

When using Jackson, I cannot seem to find a way that achieves the same thing. The closest I can get with using @JacksonXmlElementWrapper and/or JacksonXmlProperty, is a result similar to

<Root>
  <fooOrBar>
    {correct Foo serialization}
  </fooOrBar>
  <fooOrBar>
    {correct Bar serialization}
  </fooOrBar>
</Root>

CodePudding user response:

There is no Jackson-alternative to @ElementListUnion, or workaround at the moment.

  • Related