改造2解析json,从数组开始

时间:2017-03-12 12:01:52

标签: android retrofit2 gson

希望你做得好。

我发现了一个非常奇怪的问题。我通过改造2获得响应,并希望通过gson解析它。整体回应是这样的,

[ {"id":1,"name":"x","family":"y"},{"id":2,"name":"a","family":"b"},... ]

我一直在测试很多方法,但问题是每当我想得到身体的反应时。列表的大小为零或为空。

你能告诉我解析这种json的最佳方法。

如果你想要代码,我会告诉你那里。

提前致谢

3 个答案:

答案 0 :(得分:4)

它是一个对象数组。假设您的对象属于X类型,并且您的JSON字符串响应位于变量Y中,那么您应该按照以下方式对其进行解析

List<X> list =  (List<X>)new Gson().fromJSON(Y)

您的改装服务电话应该如下所示

@GET("/apiurl")
Call<List<X>> getListOfX(...)

答案 1 :(得分:1)

当您使用Retrofit libray进行Web服务调用时,您必须使用POGO类解析Json,如

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;
}

}

如您所知,响应在JsonArray中,您需要处理响应如下: -

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

答案 2 :(得分:0)

使用@Headers,传递“Accept:application / json”:

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