Gson是Google提供的方便在json數據和Java對象之間轉化的類庫。
Gson 這是使用Gson的主要類,使用它時通常先建立一個Gson實例,而後調用toJson(Object)或者from(String,Class)方法進行轉換。java
package com.example.gson; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import java.util.Date; /** * Student 實體類 * Created by liu on 13-11-25. */ public class Student { int age; String name; @Expose(serialize = true,deserialize = false) @SerializedName("bir") Date birthday; public Student(int age, String name, Date birthday) { this.age = age; this.name = name; this.birthday = birthday; } public Student(int age, String name) { this.age = age; this.name = name; } @Override public String toString() { if (birthday == null) { return "{\"name\":" + name + ", \"age\":" + age + "}"; } else { return "{\"name\":" + name + ", \"age\":" + age + ", \"birthday\":" + birthday.toString() + "}"; } } }
使用Gson前先建立Gson對象。json
//首先建立Gson實例 Gson gson = new Gson();
Student student = new Student(11, "liupan"); String jsonStr = gson.toJson(student, Student.class); Log.e("Object to jsonStr", jsonStr); Student student1 = gson.fromJson(jsonStr, Student.class); Log.e("jsonStr to Object", student1.toString());
2 List 類型和JSON字符串之間的轉換ide
Student student11 = new Student(11, "liupan11"); Student student12 = new Student(12, "liupan12"); Student student13 = new Student(13, "liupan13"); Stack<Student> list = new Stack<Student>(); list.add(student11); list.add(student12); list.add(student13);
toJsonthis
String listJsonStr = gson.toJson(list); Log.e("list to jsonStr", listJsonStr);
fromJsongoogle
Stack<Student> list2 = gson.fromJson(listJsonStr, new TypeToken<Stack<Student>>() { }.getType()); Log.e("jsonStr to list", list2.toString());
注意和上邊的簡單類型略有不一樣。.net
參考 : https://code.google.com/p/google-gson/ http://blog.csdn.net/lk_blog/article/details/7685169code