这是我准备解析的JSON格式的内容:
[
{"id":"5","version":"5.5","name":"wuwukai"},{"id":"6","version":"6.5","name":"lubenwei"},
{"id":"7","version":"7.5","name":"white"}
]
使用JSONObject:
private void parserJSONWithJSONObject(String jsonData) { try { JSONArray jsonArray = new JSONArray(jsonData); for (int i = 0;i<jsonArray.length();i++){ JSONObject jsonObject = jsonArray.getJSONObject(i); String id = jsonObject.getString("id"); String name = jsonObject.getString("name"); String version = jsonObject.getString("version"); Log.d("MainActivity","id is "+ id); Log.d("MainActivity","name is "+ name); Log.d("MainActivity","version is "+ version); } } catch (Exception e) { e.printStackTrace(); } }
在HTTP请求的地址传入json的url,然后在得到了服务器返回的数据后调用parserJSONWithJSONObject()方法来解析数据。
首先是将服务器返回的数据传入到一个JSONArray对象中,然后循环遍历这个JSONArray,从中取出每一个元素都是JSONObject对象,每个JSONObject对象中又会包含一些数据,上面例子中的json数据中包含的数据是id, name, version等。然后调用getString()方法将这些数据取出,然后做对应的操作。
使用GSON:
使用GSON解析需要先在项目中添加GSON库的依赖,编辑app/build.gradle文件,在dependencies中添加:
implementation 'com.google.code.gson:gson:2.7'
然后就可以使用GSON解析数据了。
GSON主要就是可以将一段JSON格式的字符串自动映射成一个对象,从而不需要我们再手动去编写代码进行解析。
比如:{"name":"Andy","age":"24"}
我们就可以定义一个Person类,并加入name和age这两个字段,然后只需要简单的调用如下代码就可以将JSON数据自动解析成一个Person对象了:
Gson gson = new Gson();
Person =gson.fromJson(jsonData,Person.class);
如果需要解析的是一段JSON数组,我们就需要借助TypeToken将期望解析成的数据类型传入fromJson()方法中。如下所示:
List<Person> people = gson.fromJson(jsonData,new TypeToken<List<Person>>(){}.getType();
实践使用GSON:首先新增一个APP类,并加入id, name, version这三个字段:
package com.study.xda.networktest; /** * Created by Administrator on 2018/5/15. */ public class APP { private String id; private String name; private String version; public String getId(){ return id; } public void setId(String id){ this.id = id; } public String getName(){ return name; } public void setName(String name){ this.name =name; } public String getVersion(){ return version; } public void setVersion(String version){ this.version = version; } }
然后修改MainActivity中的代码:
private void sendRequestWithOkHttp() { new Thread(new Runnable() { @Override public void run() { try { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() //指定访问的服务器地址是电脑本机 .url("http://10.0.2.2/get_data.json") .build(); Response response = client.newCall(request).execute(); String responseData = response.body().string(); showResponse(responseData); parserJSONWithGSON(responseData); } catch (IOException e) { e.printStackTrace(); } } }).start(); } private void parserJSONWithGSON(String jsonData) { Gson gson = new Gson(); List<APP> appList = gson.fromJson(jsonData , new TypeToken<List<APP>>(){}.getType()); for (APP app :appList){ Log.d("MainActivity","id is "+app.getId()); Log.d("MainActivity","name is "+ app.getName()); Log.d("MainActivity","version is "+ app.getVersion()); } }