Gson是Google開發(fā)的一個(gè)用于Java解析JSON格式的開源庫(kù)。在Android開發(fā)中,我們常常需要通過(guò)Gson對(duì)服務(wù)端返回的JSON數(shù)據(jù)進(jìn)行解析,封裝成相應(yīng)的Java對(duì)象。本文將介紹Gson庫(kù)如何解析JSON對(duì)象數(shù)組。
//定義創(chuàng)建Gson對(duì)象的方法 private static Gson getGson() { GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.setDateFormat("yyyy-MM-dd HH:mm:ss"); return gsonBuilder.create(); } //JSON格式的示例數(shù)據(jù) { "students":[ { "id":1, "name":"張三", "age":20, "score":90 }, { "id":2, "name":"李四", "age":22, "score":80 } ] } //定義學(xué)生類 public class Student { private int id; private String name; private int age; private int score; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public int getScore() { return score; } public void setScore(int score) { this.score = score; } } //解析JSON Gson gson = getGson(); String json = "JSON格式的示例數(shù)據(jù)"; JSONObject jsonObject = new JSONObject(json); JSONArray jsonArray = jsonObject.getJSONArray("students"); Liststudents = new ArrayList (); for (int i = 0; i < jsonArray.length(); i++) { JSONObject studentObject = jsonArray.getJSONObject(i); Student student = gson.fromJson(studentObject.toString(), Student.class); students.add(student); }
首先需要定義創(chuàng)建Gson對(duì)象的方法,以便使用Gson解析JSON數(shù)據(jù)。使用JSONObject將JSON字符串轉(zhuǎn)換成JSONObject對(duì)象,再通過(guò)getJSONArray方法獲取到JSONArray對(duì)象,遍歷JSONArray對(duì)象,將其中每個(gè)元素轉(zhuǎn)換成相應(yīng)的Java對(duì)象。
需要注意的是,JSON字符串中的鍵值對(duì)名字必須與Java類的屬性名完全一致,否則Gson將無(wú)法將JSON字符串映射到Java對(duì)象中。