比如微博热搜数据,结构如图:
这里需要获得card_group中每一个参数的数据,并保存为一个object,其class如下:
public class HotLine {
String pic;
String desc;
String icon;
String desc_extr;
//getter and setter
}
采用volley请求,重写parse异步处理:
@Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String parsed;
try {
parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
} catch (UnsupportedEncodingException e) {
parsed = new String(response.data);
}
JsonElement je = JsonParser.parseString(parsed);
if (je.getAsJsonObject().get("ok").getAsInt()!=1){
return Response.error(new ParseError());
}
//////////////////////////////////////////////重点部分//////////////////////////////////////////////
Type type =new TypeToken<List<HotLine>>(){}.getType();
List<HotLine> hotLineList = new Gson().fromJson(
je.getAsJsonObject().get("data").getAsJsonObject().
get("cards").getAsJsonArray().get(0).
getAsJsonObject().get("card_group").getAsJsonArray(),type);
//////////////////////////////////////////////重点部分//////////////////////////////////////////////
((FindViewModel) viewModel).getHotLineListLive().postValue(hotLineList);
Log.i("API", "微博热搜请求成功");
return Response.success(null, HttpHeaderParser.parseCacheHeaders(response));
}
重点就在标记里,先把请求得到的String
丢JsonElement
里,然后做一个List<HotLine>
的type
,然后直接从JsonElement
读到需要的card_group
的JsonArray
,用Gson
转换就行。