今天刚好遇到json数组在服务器和客户端之间的传递,所以正好学会json数组的解析,分享给大家
json数组代码
[{"music_score":"3452","comment":"It is beatiful"},{"music_score":"3452","comment":"It is beatiful"},{"music_score":"3452","comment":"It is beatiful"},{"music_score":"456321","comment":" I like it"},{"music_score":"456321","comment":"dasd"}]
在客户端通过gson解析
这里主要是通过okhttp3接收数据,我就值粘贴解析这部分的代码
public void onResponse(Call call, Response response) throws IOException {
final String res = response.body().string();
ArrayList<Music> list = new ArrayList<>();
Gson gson = new Gson();
list = gson.fromJson(res, new TypeToken<List<Music>>() {
}.getType());
Log.v("是不是json字符串:",res);
Log.v("kankanList",list.get(0).getComment());
}
看一下运行结果
V/是不是json字符串:: [{"music_score":"3452","comment":"It is beatiful"},{"music_score":"3452","comment":"It is beatiful"},{"music_score":"3452","comment":"It is beatiful"},{"music_score":"456321","comment":" I like it"},{"music_score":"456321","comment":"dasd"}]
V/kankanList: It is beatiful
正确无误,感觉通过json传递数据还是很方便,主要还是gson提供了方法可以编译和解析json数据。
下一篇,想讲解一下怎么将okhttp返回的值,返回到可用的界面。