Reputation: 528
I have a JSON object that looks like this:
[[{
"customers_id": 0
"name": "John Doe",
"address": "1234 Merry Way",
"city": "Miami",
"zipcode": "55443",
"state": "Florida"
}, {
"customers_id": 1
"name": "John Doe",
"address": "1234 Merry Way",
"city": "Miami",
"state": "Florida"
}, {
"customers_id": 2
"name": "John Doe",
"address": "1234 Merry Way",
"city": "Miami",
"state": "Florida"
}],[]
When Retrofit returns, I get the error Expected BEGIN_OBJECT but was BEGIN_ARRAY
. My call is set to return a list however:
@POST("search_clients.php")
Call<List<Course>> GetClients();
My actual retrofit call looks like this:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.build();
ClientLookup clientLookup = retrofit.create(ClientLookup.class);
Call<List<Client>> clients = clientLookup.GetClients();
clients.enqueue(new Callback<List<Client>>() {
@Override
public void onResponse(Response<List<Client>> response) {
if (!response.isSuccess()) {
Log.e(TAG, "No Success: " + response.message());
return;
}
Log.d(TAG, response.body().toString());
}
@Override
public void onFailure(Throwable t) {
Log.e(TAG, "Failure: " + t.getMessage());
}
});
And lastly my model looks like this:
public class Client {
private int customers_id;
private String name;
private String address;
private String city;
private String zipcode;
private String state;
}
And lastly a custom converter to remove the leading [ and trailing ,[]
public final class ClientCleaner extends Converter.Factory {
private static final String TAG = ClientCleaner.class.getName();
@Override
public Converter<ResponseBody, Client> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
return new Converter<ResponseBody, Client>() {
@Override
public Client convert(ResponseBody body) throws IOException {
String returnValue = body.string();
if (returnValue.startsWith("[")){
returnValue = returnValue.substring(1);
}
if (returnValue.endsWith(",[]]")){
returnValue = returnValue.substring(0, returnValue.length() - 4);
}
Log.d(TAG, returnValue);
Gson gson = new Gson();
return gson.fromJson(returnValue, Client.class);
}
};
}
}
Any idea why my call is still expecting a BEGIN_OBJECT?
Upvotes: 0
Views: 2060
Reputation: 2796
Deserializing of the list is not correct. Refer to this SO question about how to deserialize a list of objects with Gson.
This should be sufficient:
List<Client> videos = gson.fromJson(returnValue, new TypeToken<List<Client>>(){}.getType());
Upvotes: 3