Skip to content
Advertisement

How to deserialise anonymous array of mixed types with Jackson

In my Java program, I am trying to parse data that I get from Strava.com‘s API. One of the JSON payloads, I receive from there looks as follows:

JavaScript

Basically, four of these entries (altitude, velocity_smooth, distance and time) have the same structure (their data field is an array of doubles (or ints that can be parsed as doubles)), but the second entry (latlng) has a slighlty different structure for the data field (it is a an array of arrays of double).

I am familiar with the Jackson library to convert between JSON and POJOs if all the content is named, but do not see how I can model the above data structure to deserialise it.

Let’s say that instead of the data above, it looked as follows:

JavaScript

Then I could define the following three classes

JavaScript

And then use

JavaScript

to read in that object. However, as the data received from Strava is an array instead of an object, I am failing. I have read Baeldung’s article on how to unmarshal to collections/arrays but that assumes that all classes in the array/collection are the same.

I though about defining an interface which would be extended by the two classes that could be found in the array and then use that mechanism:

JavaScript

But that doesn’t work, as I would need to find some way to let it find out when to use a DoubleData class and when to use a CoordinateData class.

I am sure, I am not the first person trying to use Strava data in Java. Can this be done?

Advertisement

Answer

If possible, you should definitely use their’s client. Strava API v3 shows many examples how to use this API together with theirs model.

If you want to implement your own model you should consider inheritance and com.fasterxml.jackson.annotation.JsonTypeInfo, com.fasterxml.jackson.annotation.JsonSubTypes annotations. Also, JSON Object with type latlng contains list of objects which are represented in JSON in form of array. We can handle this using com.fasterxml.jackson.annotation.JsonFormat annotation. All together gives:

JavaScript

Above code prints:

JavaScript

You should also take a look on Google Dev Group and consult this solution.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement