We have an API endpoint that receives XML data fro...
# announcements
l
We have an API endpoint that receives XML data from a 3rd party provider. The data itself is basically a list of elements, where each can be one of many different polymorphic types. They all share some attributes (say they all have a created_at="") and then some specific per element. Looked into using Jackson but it all seem very cumbersome, whats' the easiest way to parse this XML? An example could be
Copy code
<?xml version="1.0" encoding="UTF-8">
<provider version="1.0">
  <update id="12313">
    <event name="hello" created_at="2019-12-14" />
    <event name="world" created_at="2019-12-16" />
    <country where="us" created_at="2019-15-16" />
  </update>
</provider>
Basically want to end up with a class containing
ProviderUpdate(id: String, updates: List<Update>)
where
Update
is either an interface, class, sealed class or something, that can either be
Event
or
Country
or etc
w
I assume you've looked at stuff like this https://medium.com/@foxjstephen/how-to-actually-parse-xml-in-java-kotlin-221a9309e6e8 which doesn't seem too difficult to me.
l
@Wesley Acheson The XML example is too simple unfortunately, don't see any polymorphism
m
Try having a look at the official docs: https://github.com/FasterXML/jackson-docs/wiki/JacksonPolymorphicDeserialization The idea is to use
@JsonTypeInfo
and
@JsonSubTypes
to declare the expected types: https://www.mkammerer.de/blog/jacksons-polymorphic-deserialization/ The annotations are the same for JSON, but you’ll need to use an
XmlMapper
instead of
ObjectMapper