简体   繁体   中英

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

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(...)

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

Use @Headers, passing "Accept: application/json":

@GET("/list")
@Headers({"Accept: application/json"})
Call<List<User>> getList()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM