摘自《第一行代码——Android(第二版)》
9.4.2 使用GSON
如果你认为使用JSONObject来解析JSON数据已经非常简单了,那你就太容易满足了。谷歌提供的GSON开源库可以让解析JSON数据的工作简单到让你不敢想象的地步,那我们肯定是不能错过这个学习机会的。
不过GSON并没有被添加到Android官方的API中,因此如果想要使用这个功能的话,就必须要在项目中添加GSON库的依赖。编辑app/build.gradle文件,在dependencies闭包中添加如下内容:
dependencies {compile fileTree(dir: ‘libs’, include: [’*.jar’])
testCompile ‘junit:junit:4.12’
compile ‘com.android.support:appcompat-v7:24.2.1’
compile ‘com.squareup.okhttp3:okhttp:3.4.1’
compile 'com.google.code.gson:gson:2.7’
}
那么GSON库究竟是神奇在哪里呢?其实它主要就是可以将一段JSON格式的字符串自动映射成一个对象,从而不需要我们再手动去编写代码进行解析了。
比如说一段JSON格式的数据如下所示:
{“name”:“Tom”,“age”:20}
那我们就可以定义一个Person 类,并加入name 和age 这两个字段,然后只需简单地调用如下代码就可以将JSON数据自动解析成一个Person 对象了:
Gson gson = new Gson();
Person person = gson.fromJson(jsonData, Person.class);
如果需要解析的是一段JSON数组会稍微麻烦一点,我们需要借助TypeToken将期望解析成的数据类型传入到fromJson() 方法中,如下所示:
List<Person> people = gson.fromJson(jsonData, new TypeToken<List<Person>>() {}.getType());
下面总结一个小demo:
好了,基本的用法就是这样,下面就让我们来真正地尝试一下吧。首先新增一个App 类,并加入id 、name 和version 这3个字段,如下所示:
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中的代码,如下所示:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
...
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();
parseJSONWithGSON(responseData);//调用此方法解析json数据源
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
...
private void parseJSONWithGSON(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());
}
}
}
打印出解析的json数据