你现在有这么一串玩意儿:
{ "status":1, "message":"获取成功", "data":[ { "version":"20170317", "sub_version":"1", "start_time":"1489735453", "end_time":"1489860122", "url":"http://konoha.com/yukino.zip", "md5":"1b7a5fff59162dd50fd81607c37259e6" }, { "version":"20170319", "sub_version":"2", "start_time":"1489860122", "end_time":"1490032922", "url":"http://konoha.com/yuigahama.zip", "md5":"248e8ae66ce46ebe5b7bd51cc716a025" } ] }
你可以使用 Gson 来解析这玩意儿。
首先你需要建立一个类,来让 Gson 将这对玩意儿转成 Java 对象,一般我们称这种类为 JavaBean (大概)。
那就新建一个叫做 ThemeBean 的类,然后建立对象:
[ThemeBean.java] public class ThemeBean { public int status; public String message; public List data; public static class Data{ public int version; public int sub_version; public long start_time; public long end_time; public String url; public String md5; } }
然后在你的 Activity 里 (这里的情况是在 Android 里使用) 写个方法来解析,就像这样:
private void konoha(String json) { Gson gson = new Gson(); ThemeBean themeBean = gson.fromJson(json, ThemeBean.class); LogUtil.debug("status: " + themeBean.status); LogUtil.debug("message: " + themeBean.message); for (int i = 0; i < themeBean.data.size(); i++) { LogUtil.debug("version: " + themeBean.data.get(i).version); LogUtil.debug("sub_version: " + themeBean.data.get(i).sub_version); LogUtil.debug("start_time: " + themeBean.data.get(i).start_time); LogUtil.debug("end_time: " + themeBean.data.get(i).end_time); LogUtil.debug("url: " + themeBean.data.get(i).url); LogUtil.debug("md5: " + themeBean.data.get(i).md5); } }
这样你就能在 Log 里获得所有数据啦。
这个方法需要传入的 String 一般是服务器返回的,如果只是临时使用一下的话可能用 OkHttp 访问服务器获得,比如:
private void sendRequestWithOkHttp() { new Thread(new Runnable() { @Override public void run() { try { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url("http://pan.plyz.net/s/?u=555114218&p=theme.json").build(); Response response = client.newCall(request).execute(); String responseData = response.body().string(); test(responseData); } catch (IOException e) { e.printStackTrace(); } } }).start(); }
使用的时候调用一下这个方法就可以啦。