How to deserialize json starting with an array via google-api-client
-
18-04-2021 - |
Вопрос
Much like How to deserialize JSON file starting with an array in Jackson? I have a JSON REST reply that looks like
[
{
something
},
{
something
},
...
]
Problem is that the array is toplevel. I tried calling com.google.api.client.http.json.JsonHttpParser
as follows:
Something[] result = jsonParser.parse(response, Something[].class); //array cannot be instantiated: java.lang.IllegalArgumentException: unable to create new instance of class [L...; because it is an array
List<Something> result = jsonParser.parse(response, List.class); //interface cannot be instantiated: java.lang.IllegalArgumentException: unable to create new instance of class java.util.List because it is an interface and because it has no accessible default constructor
ArrayList<Something> result = jsonParser.parse(response, ArrayList.class); //throws IllegalArgumentException: START_ARRAY
where Something
is my model class that should allow deserialization of an element. None of these alternatives work. The stacktrace on the last one is:
01-21 18:44:15.649: E/AndroidRuntime(3117): Caused by: java.lang.IllegalArgumentException: START_ARRAY
01-21 18:44:15.649: E/AndroidRuntime(3117): at com.google.common.base.Preconditions.checkArgument(Preconditions.java:88)
01-21 18:44:15.649: E/AndroidRuntime(3117): at com.google.api.client.json.JsonParser.startParsingObject(JsonParser.java:161)
01-21 18:44:15.649: E/AndroidRuntime(3117): at com.google.api.client.json.JsonParser.parse(JsonParser.java:233)
01-21 18:44:15.649: E/AndroidRuntime(3117): at com.google.api.client.json.JsonParser.parse(JsonParser.java:224)
01-21 18:44:15.649: E/AndroidRuntime(3117): at com.google.api.client.json.JsonParser.parseAndClose(JsonParser.java:180)
01-21 18:44:15.649: E/AndroidRuntime(3117): at com.google.api.client.json.JsonParser.parseAndClose(JsonParser.java:120)
01-21 18:44:15.649: E/AndroidRuntime(3117): at com.google.api.client.http.json.JsonHttpParser.parse(JsonHttpParser.java:62)
How should I do this?
Решение
The google-api-client 1.4.1 classes just seem to rely on creating new instances and only working with START_OBJECT, not START_ARRAY, in this area, meaning they don't support toplevel arrays.
I couldn't workaround this and I solved it by updating everything to google-api-client 1.6.0, which is quite a large update and refactor effort.