说明
比起XML,JSON的主要优势在于它的体积更小,在网络上传输的时候可以更省流量,但缺点在于,他的语义性较差,看起来不如XML直观。
解析方式
- 官方提供的JSONObject
- 谷歌开源库的GSON
- 第三方开源库,Jackson、FastJSON
模拟一组JSON数据
下面使用JSONObject和GSON分别解析这组数据.
[
{"id":"1","name":"Tom","sex":"男"},
{"id":"2","name":"Jack","sex":"男"},
]
使用JSONObject
private void parseJSONWithJSONObject(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 sex= jsonObject.getString("sex");
}
}catch(Exception e){
e.printStackTrace();
}
}
使用GSON
GSON并没有添加到Android官方的API中,因此想使用的话,需在dependencies闭包中添加如下内容
compile 'com.google.code.gson:gson:2.7'
接下来,新建People类
public class People {
private String id;
private String name;
private String sex;
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 getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
进行解析
private void parseJSONWithGSON(String jsonData) {
Gson gson = new Gson();
List<People> peopleList = gson.fromJson(jsonData, new TypeToken<List<People>>() {}.getType());
for (People people : peopleList) {
String id = people.getId();
String name = people.getName();
String sex = people.getSex();
}
}