Android使用GSON将JSONArray转换为List <class>

时间:2019-04-22 13:40:13

标签: android gson retrofit

当我想从我们的Web服务获取列表时,将其结果返回为JSONArray

[{
  "b_code": 1,
  "c_code": 4,
  "f_code": 5462,
  "f_date": "\/Date(1555270200000+0430)\/",
  "f_meghdar": 11,
  "k_code": 1,
  "k_count": 150,
  "k_pay": 1500,
  "kalanam": "",
  "o_anbar": "",
  "o_code": 1,
  "o_date": "\/Date(1555183800000+0430)\/",
  "o_rasmi": true,
  "u_code": 0
}, 
...
]

现在,当我将该数组转换为List<Offers>的类时,例如:

Gson gson = new Gson();
Type type = new TypeToken<List<Offers>>() {}.getType();
List<Offers> contactList = gson.fromJson(response.body().toString(), type);

我收到此错误:

java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 2 path $[0]

response.body()输出:

response.body() = {ArrayList@12995}  size = 4
 0 = {Offers@13020} 
 1 = {Offers@13021} 
 2 = {Offers@13022} 
 3 = {Offers@13023} 

Offers类结构:

public class Offers{
    @SerializedName("b_code")
    private Long mBCode;

    @SerializedName("c_code")
    private Long mCCode;

    @SerializedName("f_code")
    private Long mFCode;

    @SerializedName("f_date")
    private String mFDate;

    @SerializedName("f_meghdar")
    private Long mFMeghdar;

    @SerializedName("k_code")
    private Long mKCode;

    @SerializedName("k_count")
    private Long mKCount;

    @SerializedName("k_pay")
    private Long mKPay;

    @SerializedName("kalanam")
    private String mKalanam;

    @SerializedName("o_anbar")
    private String mOAnbar;

    @SerializedName("o_code")
    private Long mOCode;

    @SerializedName("o_date")
    private String mODate;

    @SerializedName("o_rasmi")
    private Boolean mORasmi;

    @SerializedName("u_code")
    private Long mUCode;

    /*GETTERS AND SETTERS*/
}

2 个答案:

答案 0 :(得分:0)

使用方式如下

Gson gson = new Gson();
Type type = new TypeToken<List<Offers>>() {}.getType();
List<Offers> contactList = gson.fromJson(response.body().string(), type);

答案 1 :(得分:0)

在使用Retrofit时,不必使用gson来解析JSON。调用response.body()时,翻新会自动将JSON字符串转换为pojo元素。

当前,当您执行response.body().toString()时,它首先将主体转换为List<Offer>,然后在toString()对象上调用List<Offers>。这就是为什么您要

0 = {Offers@13020} 
 1 = {Offers@13021} 
 2 = {Offers@13022} 
 3 = {Offers@13023} 

问题必须出在您的API接口中。您可能为该方法定义了错误的返回变量。

例如。

如果您的根元素是

[{
  "b_code": 1,
  "c_code": 4,
  "f_code": 5462,
  "f_date": "\/Date(1555270200000+0430)\/",
  "f_meghdar": 11,
  "k_code": 1,
  "k_count": 150,
  "k_pay": 1500,
  "kalanam": "",
  "o_anbar": "",
  "o_code": 1,
  "o_date": "\/Date(1555183800000+0430)\/",
  "o_rasmi": true,
  "u_code": 0
}, 
...
]

然后您的API interface方法应该是这样的

@GET("get_offers")
Call<**List<Offers>**> getOffers();