I've had some trouble deserializing an object that contains 0 to many child objects that can either contains a string or a string array for a particular value.
Here's an example JSON
{
"name": "process name",
"tasks": [{
"name": "task 1",
"fields": [{
"name": "field 1",
"value": "123abc"
},
{
"name": "field 2",
"value": ["value 1", "value 2"]
}
]
},
{
"name": "task 2",
"fields": []
}]
}
I have a Java entity setup to match this structure like this:
public class Process {
public Process() {}
public String name;
public Task[] tasks;
}
public class Task {
public Task() {}
public String name;
public Field[] fields;
}
public class Field {
public Field() field;
public String name;
public String value;
}
And I deserialize like such:
static <T> T fetch(MyHttpRequest request, Class<T> entity)
{
String response = sendRequestAndParse(request);
if (response == null) {
log.debug(String.format("API response was null %n)"));
return null;
}
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
return gson.fromJson(response, entity);
}
I use dynamic types because there's a number of other entities other than Process that I use this same method for. But I can't figure out how to handle the case where the field value can be either a string to an array of string. Any pointers would be appreciated.