I am working on an Android app that uses Retrofit+OkHttp to connect to a REST API and consume JSON data. I'm fairly new to Retrofit, so I'm still learning how it works, but so far it's been pretty smooth. However, I ran into an unusual problem.
One of the endpoints returns data that looks a bit like this:
{
"success": true,
"data": [
[
{
"field": "value1",
...
},
{
"field": "value2",
...
},
...
],
{
"info": "value",
"info2": "value",
"info3": "value",
}
],
"message": "This is the message."
}
For the most part, this is a pretty standard JSON response. We have a "status" value, a "message", and a "data" value containing the important data being returned. However, there's a problem with the structure of "data". As you can see, it's an array, but it's not just an array of objects. Its first element is the array of values, and its second element is an object.
Gson doesn't like this. If I want to create a POJO to parse this into using Gson, I would expect to do something like this:
public class JsonResponse {
@SerializedName("success")
@Expose
boolean success;
@SerializedName("message")
@Expose
String message;
@SerializedName("data")
@Expose
private ArrayList<MyObject> data = new ArrayList<>();
public ArrayList<MyObject> getData() {
return data;
}
public void setData(ArrayList<MyObject> data) {
this.data = data;
}
}
Where "MyObject" is a Parcelable like this:
public class MyObject implements Parcelable {
@SerializedName("field")
@Expose
boolean field;
...
}
But that doesn't work, because "data" isn't just an array of objects; it's an array containing the array of objects and another top-level object.
I can define "data" as "Array", and it does seem to parse the values. But then they come out as generic LinkedTreeMap objects, so I lose the advantages of Gson's JSON->POJO parsing.
Is there an elegant way to handle a mixed array like this in Retrofit/Gson? I'm not responsible for the data coming from the API, so I don't think changing that will be an option.