这是主要说我们平时遇到的JSON串最外层是数组的情况
第一种,Type的方式
List<Result> datas=new ArrayList<>();
//获取集合数据的type
Type type= new TypeToken<List<Result>>(){}.getType();
Gson gson=new Gson();
datas=gson.fromJson(str,type);
Log.d("zzz",datas.size()+"---");
for(Result r:datas){
Log.d("zzz",r.toString());
}
原生解析,以当前的json串为例
try {
JSONArray array=new JSONArray(str);
for(int i=0;i<array.length();i++){
Result result=new Result();
JSONObject obj=array.optJSONObject(i);
String img3=obj.optString("img3");
String name=obj.optString("name");
double price=obj.optDouble("price");
double tgprice=obj.optDouble("tg_price");
result.setImg3(img3);
result.setName(name);
result.setPrice(price);
result.setTg_price(tgprice);
datas.add(result);
}
} catch (JSONException e) {
e.printStackTrace();
}
混合解析
try {
Gson gson=new Gson();
JSONArray array=new JSONArray(str);
for(int i=0;i<array.length();i++){
JSONObject object=array.optJSONObject(i);
Result r=gson.fromJson(object.toString(),Result.class);
datas.add(r);
}
} catch (JSONException e) {
e.printStackTrace();
}
这三个方式都是以最外层是数组的例子写的,可以参考看看。