數據解析之JSON
數據結構
- Object (對象,在花括號中)
- Array (數組,在方括號中)
基本類型
- String 字符串(在雙引號中)
- number 數字(整數或浮點數)
- 邏輯值 (true,false)
- null 數據爲空
示例
[{
"name":"張三",
"age":23,
"birthday":"1994-01-01",
"school":"藍翔",
"major":[
"理髮",
"挖掘機"
],
"married":false,
"car":"大衆"},
{
"name":"小紅",
"age":20,
"birthday":"1996-01-01",
"school":"清華",
"major":[
"理髮",
"化妝"
],
"married":true,
"car":null}
]
Json解析的三種方法
根據Json信息建立javaBean類
public class People {
private String name;
private int age;
private String birthday;
private String school;
private List<String> major;
private boolean married;
private String car;
getter and setter methods...
@Override
public String toString() {
return "People{" +
"name='" + name + '\'' +
", age=" + age +
", birthday='" + birthday + '\'' +
", school='" + school + '\'' +
", major=" + major +
", married=" + married +
", car='" + car + '\'' +
'}';
}
}
1.使用JSONObject
1.1使用getXXX()方法
代碼不會去判斷是否存在該字段,需要你自己去判斷,否則的話會報錯。自己判斷的話使用has(String name)來判斷
private void parseJsonWithJSONObject(String jsonStr) {
try {
//peopleList用於存儲所有People信息
List<People> peopleList=new ArrayList<>();
//獲取的json字符串是一個JSONArray對象,其他數據結構還有JSONObject
JSONArray root=new JSONArray(jsonStr);
//遍歷JSONArray中的JSONObject對象
for (int i = 0; i < root.length(); i++) {
//新建people對象,存儲解析後的people信息
People people=new People();
JSONObject obj = (JSONObject) root.get(i);
//解析當前JSONObject包含的信息
String name=obj.getString("name");
int age=obj.getInt("age");
String birthday=obj.getString("birthday");
String school=obj.getString("school");
JSONArray major=obj.getJSONArray("major");
List<String> majors=new ArrayList<>();
//major是一個JSONArray,對其執行遍歷
for (int j = 0; j <major.length() ; j++) {
String item= (String) major.get(j);
majors.add(item);
}
boolean married=obj.getBoolean("married");
String car=obj.getString("car");
people.setName(name);
people.setAge(age);
people.setBirthday(birthday);
people.setSchool(school);
people.setMajor(majors);
people.setMarried(married);
people.setCar(car);
peopleList.add(people);
Log.e(TAG, "parseJson: "+people.toString() );
}
} catch (JSONException e) {
e.printStackTrace();
}
}
1.2使用optXXX()方法
這些方法在解析時,如果對應字段不存在會返回空值或者0,不會報錯
private void parseJsonWithJSONObject2(String jsonStr) {
try {
JSONArray root=new JSONArray(jsonStr);
for (int i = 0; i < root.length(); i++) {
People people=new People();
JSONObject obj=root.getJSONObject(i);
people.setName(obj.optString("name"));
people.setAge(obj.optInt("age"));
people.setBirthday(obj.optString("birthday"));
people.setSchool(obj.optString("school"));
JSONArray majors=obj.optJSONArray("major");
List<String> majorList=new ArrayList<>();
for (int j = 0; j <majors.length() ; j++) {
majorList.add(majors.optString(j));
}
people.setMajor(majorList);
people.setMarried(obj.optBoolean("married"));
people.setCar(obj.optString("car"));
Log.e(TAG, "parseJson2: "+people.toString() );
}
} catch (JSONException e) {
e.printStackTrace();
}
}
2.使用Gson(簡單方便)
需要添加依賴
compile 'com.google.code.gson:gson:2.8.1'
方法:
private void parseJsonWithGson(String jsonStr) {
Gson gson=new Gson();
//若解析的是JSONObject對象,很簡單,可以這樣
//WeatherResponse response=gson.fromJson(jsonStr,WeatherResponse.class);
//解析的是Json數組,需要藉助TypeToken將期望解析成的數據類型傳入到fromJson()方法中
List<People> response=gson.fromJson(jsonStr,new TypeToken<List<People>>(){}.getType());
Log.e(TAG, "parseJsonWithGson: "+response.toString() );
}
另外:通過GsonFormat可以快速生成bean類,只需要將要解析的json流拖到框中
GsonFormat是一個插件,需在在File>Settings>Plugins中勾選
Gson支持Date類型,在定義bean類時,對日期可定義爲Data類型
//bean類
private Date birthday;
//解析
Gson gson=new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
...
//解析結果:
birthday=Sat Jan 01 00:00:00 GMT+08:00 1994
//在toString()中執行birthday.toLocaleString()顯示如下:
birthday=1994年1月1日 00:00:00
3.使用JsonReader
private void parseJsonWithJsonReader(String jsonStr) {
JsonReader reader = new JsonReader(new StringReader(jsonStr));
try {
// 遇到[,開始解析數組
reader.beginArray();
List<People> peopleList = new ArrayList<>();
while (reader.hasNext()) {
// 遇到{,開始解析對象
reader.beginObject();
People people = new People();
// 新建major集合
List<String> majors = new ArrayList<>();
while (reader.hasNext()) {
String tag = reader.nextName();
if ("name".equals(tag)) {
people.setName(reader.nextString());
}
if ("age".equals(tag)) {
people.setAge(reader.nextInt());
}
if ("birthday".equals(tag)) {
people.setBirthday(reader.nextString());
}
if ("school".equals(tag)) {
people.setSchool(reader.nextString());
}
if ("major".equals(tag)) {
// 遇到[,開始解析數組
reader.beginArray();
while (reader.hasNext()) {
majors.add(reader.nextString());
}
// 遇到],數組解析結束
reader.endArray();
people.setMajor(majors);
}
if ("married".equals(tag)) {
people.setMarried(reader.nextBoolean());
}
if ("car".equals(tag)) {
//值類型爲null時會報錯
reader.skipValue();
}
}
// 遇到},對象解析結束
reader.endObject();
peopleList.add(people);
}
// 遇到],數組解析結束
reader.endArray();
Log.e(TAG, "parseJsonReader: " + peopleList.toString());
} catch (IOException e) {
e.printStackTrace();
}
}