我有这种JSON响应
{"error":false,"country":"United Kingdom","country_id":"903",
"currency":"GBP","product_list":["5","10","15","20","25","30","40","50"]}
并且我能够解析国家,国家/地区和货币,没有问题,当我尝试解析产品列表时,问题就从产品列表开始!代码下方
try {
boolean error = response.getBoolean("error");
if (!error){
String country = response.getString("country");
int country_id = response.getInt("country_id");
String currency = response.getString("currency");
List<Tarif> tarifs = new
Gson().fromJson(response.getJSONArray("product_list").toString(), new
TypeToken<List<Tarif>>(){}.getType());
new DtoneTarifs(country, country_id, currency, tarifs);
}
}
这是我的Tarif和其他班级
public class Tarifs {
public String country;
public int country_id;
public String currency;
public List<Tarif> tarifList;
public Tarifs (String country, int country_id, String currency, List<Tarif> tarif){
this.country = country;
this.country_id = country_id;
this.currency = currency;
this.tarifList = tarif;
}
}
我想在Tarif类中填写product_list,其中只有一个参数接受并在recycler_view中显示它们
{"error":false,"country":"United Kingdom","country_id":"903",
"currency":"GBP","product_list":["5","10","15","20","25","30","40","50"]}
您可以看到product_list是字符串值的JSON数组。但是您正在将其转换为Tarif类型的列表。应该将其转换为字符串类型列表。
将Tarif的值设置为JSON Array的自定义对象,或将列表类型更改为字符串。
应该是这样:
try {
boolean error = response.getBoolean("error");
if (!error){
String country = response.getString("country");
int country_id = response.getInt("country_id");
String currency = response.getString("currency");
List<String> tarifs = new
Gson().fromJson(response.getJSONArray("product_list").toString(), new
TypeToken<List<String>>(){}.getType());
Tarifs result = new Tarifs(country, country_id, currency, tarifs);
}
}
关税课
public class Tarifs {
public String country;
public int country_id;
public String currency;
public List<String> tarifList;
public Tarifs (String country, int country_id, String currency, List<String> tarif){
this.country = country;
this.country_id = country_id;
this.currency = currency;
this.tarifList = tarif;
}
}
您去这里!