Mehdi Jahed Manesh Mehdi Jahed Manesh - 9 months ago 83
Android Question

Retrofit 2 parsing json , starting with array

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

Answer Source

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