編輯:關於 Android 程式設計
Gson 是 Google 提供的 JSON 序列化/反序列化工具,能把 Java 物件與 JSON 字串互相轉換,大幅簡化資料處理。以下用一系列範例,示範各種常見場景的用法。
GsonBuilder builder = new GsonBuilder(); // 不轉換沒有 @Expose 註解的欄位 builder.excludeFieldsWithoutExposeAnnotation(); Gson gson = builder.create();
// 物件轉 string
Student stu = new Student();
stu.setStudentId(333);
stu.setStudentName("qqq");
String stuStr = gson.toJson(stu);
System.out.println(stuStr); // {"studentName":"qqq","studentId":333}
// string 轉物件
Student user2 = gson.fromJson(stuStr, Student.class);
System.out.println(user2);
String stuTemp = "{\"studentName\":\"qqq2\",\"studentId\":3335}";
Student user4 = gson.fromJson(stuTemp, Student.class);
System.out.println(user4);
集合需要透過 TypeToken 指定型別資訊,Gson 才能正確還原:
List<Student> testBeanList = new ArrayList<Student>();
Student testBean = new Student();
testBean.setStudentId(555);
testBean.setStudentName("552");
testBeanList.add(testBean);
Type type = new TypeToken<List<Student>>(){}.getType(); // 指定集合物件屬性
String beanListToJson = gson.toJson(testBeanList, type);
System.out.println(beanListToJson); // [{"studentName":"552","studentId":555}]
// 集合 string 轉回物件 list
List<Student> testBeanListFromJson = gson.fromJson(beanListToJson, type);
System.out.println(testBeanListFromJson); // [555:552]
List<String> testList = new ArrayList<String>();
testList.add("first");
testList.add("second");
String listToJson = gson.toJson(testList);
System.out.println(listToJson); // ["first","second"]
// 集合字串轉回來需要指定型別
List<String> testList2 = (List<String>) gson.fromJson(listToJson,
new TypeToken<List<String>>() { }.getType());
System.out.println(testList2);
Map<String, String> testMap = new HashMap<String, String>();
testMap.put("id", "id.first");
testMap.put("name", "name.second");
String mapToJson = gson.toJson(testMap);
System.out.println(mapToJson); // {"id":"id.first","name":"name.second"}
Map<String, String> userMap2 = (Map<String, String>) gson.fromJson(mapToJson,
new TypeToken<Map<String, String>>() { }.getType());
System.out.println(userMap2); // {id=id.first, name=name.second}
當一個物件同時包含單一子物件、List 與 Map 時,Gson 依然能處理:
Student user1 = new Student();
user1.setStudentId(1001);
user1.setStudentName("張三");
Student user3 = new Student();
user3.setStudentId(1002);
user3.setStudentName("李四");
Map<String, Student> userMap = new HashMap<String, Student>();
userMap.put("user1", user1);
userMap.put("user3", user3);
List<Student> userList = new ArrayList<Student>();
userList.add(user1);
userList.add(user3);
Teacher groupBean = new Teacher();
groupBean.setStudent(user1);
groupBean.setStus(userList);
groupBean.setMap((HashMap) userMap);
Gson gsonGroup = new Gson();
String sGroupBean = gsonGroup.toJson(groupBean, new TypeToken<Teacher>() { }.getType());
System.out.println(sGroupBean);
// 複雜物件 string 轉物件
Teacher groupBean2 = (Teacher) gson.fromJson(sGroupBean, new TypeToken<Teacher>() { }.getType());
System.out.println(groupBean2);
使用 @Expose 註解標示需要參與序列化的欄位:
public class Student {
@Expose
private String studentName;
@Expose
private int studentId;
public Student() {}
public Student(int studentId, String studentName) {
this.setStudentId(studentId);
this.setStudentName(studentName);
}
public String toString() {
return this.getStudentId() + ":" + this.getStudentName();
}
public String getStudentName() { return studentName; }
public void setStudentName(String studentName) { this.studentName = studentName; }
public int getStudentId() { return studentId; }
public void setStudentId(int studentId) { this.studentId = studentId; }
}
public class Teacher {
@Expose private int id;
@Expose private String name;
@Expose private int age;
@Expose private Student student;
@Expose private List stus;
@Expose private HashMap map;
public String toString() {
return this.getId() + ":" + this.getName() + ":" + this.getAge()
+ ":" + this.getStudent().toString()
+ ":" + this.getStus() + ":" + this.getMap();
}
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 Student getStudent() { return student; }
public void setStudent(Student student) { this.student = student; }
public List getStus() { return stus; }
public void setStus(List stus) { this.stus = stus; }
public HashMap getMap() { return map; }
public void setMap(HashMap map) { this.map = map; }
}
掌握一個要訣:凡是集合與 Map,序列化與反序列化時都要用 TypeToken 帶上型別資訊,Gson 才能在泛型擦除的情況下正確還原資料。
android——View / ViewGroup 的「生命週期」調用順序
自定義控件的很多奇怪問題,根源都出在「方法調用順序沒搞清楚」。把 View 與 ViewGroup 的關鍵回調串起來看,會清晰很多。 完整調用鏈 1. Activity
Android ListView 加入 CheckBox 的實作原理與完整程式碼
在 ListView 裡放入 CheckBox,看似簡單,實則暗藏不少細節,特別是效能優化與事件處理。本文透過一個可全選、可取消的範例,帶你理解它的運作原理與實作重點。
Android新建Activity的三個步驟詳解
在一個Android專案裡,究竟該怎麼新增一個Activity?其實只要掌握三個步驟即可,本文就為大家完整示範。 第一,新建一個類(*.class),讓它繼承自andro
用 Android Animation 做一個 loading 動畫
Animation 的用法門檻不高,這裡用一個 loading 效果把四種動畫都串一遍。 先看效果: Android 的 Animation 體系提供四種基本動畫: A