Reputation: 2278
Hope you are doing well .
I found a problem which is really weird . I get the response via retrofit 2 and wanna pars it via gson . The Whole response is like this ,
[ {"id":1,"name":"x","family":"y"},{"id":2,"name":"a","family":"b"},... ]
I have been testing many ways , but the problem is whenever I want to get response from body . The size of list is zero or null .
Can you show me the best way to parse this type of json .
If you want the code , I`ll show you there .
Thanks in advance
Upvotes: 3
Views: 2227
Reputation: 1244
Use @Headers, passing "Accept: application/json":
@GET("/list")
@Headers({"Accept: application/json"})
Call<List<User>> getList()
Upvotes: 0
Reputation: 8042
As you are using the Retrofit
libray to web service calling than u will have to parse the Json using the POGO class like
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class YourPareseClass{
@SerializedName("id")
@Expose
private Integer id;
@SerializedName("name")
@Expose
private String name;
@SerializedName("family")
@Expose
private String family;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getFamily() {
return family;
}
public void setFamily(String family) {
this.family = family;
}
}
As you know that the response is in the JsonArray than , you need to handle the response are as follow:-
Type collectionType = new TypeToken<Collection<YourPareseClass>>(){}.getType();
Collection<YourPareseClass> YOUR_RESONSE_ARRAY = gson.fromJson("YOUR_JSON_RESONSE", collectionType); ///YOUR_RESONSE_ARRAY contains all yours response in the Array
Upvotes: 1
Reputation: 5335
Its an array of objects. Say your object is of type X
and your JSON
string response is in variable Y then you should be parse it in following way
List<X> list = (List<X>)new Gson().fromJSON(Y)
And your retrofit service call should look like this
@GET("/apiurl")
Call<List<X>> getListOfX(...)
Upvotes: 4