I've created a simple REST endpoint:
http://<server_address>:3000/sizes
This URL returns a very simple response containing a json array as follows:
[
{ "id": 1, "name": "Small", "active": true },
{ "id": 2, "name": "Medium", "active": true },
{ "id": 3, "name": "Large", "active": true }
]
Now, I'm trying to consume this response using Retrofit 2 with GSON.
I've added a model:
@lombok.AllArgsConstructor
@lombok.EqualsAndHashCode
@lombok.ToString
public class Size {
private int id;
private String name;
private boolean active;
@SerializedName("created_at")
private String createdAt;
@SerializedName("updated_at")
private String updatedAt;
}
And service:
public interface Service {
@GET("sizes")
Call<List<Size>> loadSizes();
}
I've instantiated a Retrofit:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://<server_address>:3000")
.addConverterFactory(GsonConverterFactory.create())
.build();
And my service:
Service service = retrofit.create(Service.class);
Now, trying to call the data:
service.loadSizes().enqueue(new Callback<List<Size>>() {
@Override
public void onResponse(Call<List<Size>> call, Response<List<Size>> response) {
for(Size size: response.body()) {
System.out.println(size.toString());
}
}
@Override
public void onFailure(Call<List<Size>> call, Throwable t) {
System.out.println(t.getMessage());
}
});
What ends up with an exception:
java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 18 path $[0].name
I suppose the error is caused by that, the REST API returns a response which is an array nor object.
- Am I correct?
- What is the easiest way to make this code to work?
REST service cannot be modified, so the response must stay as is.
Also, deserialization of the above json using pure GSON might be done by:
Type sizesType = new TypeToken<List<Size>>(){}.getType();
List<Size> size = new Gson().fromJson(json, sizesType);
But I have no idea how to make Retrofit 2 to use this.
Thanks in advance.