Gson是Google提供的方便在json数据和Java对象之间转化的类库。 Gson地址
Gson
这是使用Gson的主要类,使用它时一般先创建一个Gson实例,然后调用toJson(Object)或者from(String,Class)方法进行转换。
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对象。
//首先创建Gson实例
Gson gson = new Gson();
1. toJson,fromJson 简单对象之间的转化
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字符串之间的转换
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);
toJson
String listJsonStr = gson.toJson(list);
Log.e("list to jsonStr", listJsonStr);
fromJson
Stack<Student> list2 = gson.fromJson(listJsonStr, new TypeToken<Stack<Student>>() {
}.getType());
Log.e("jsonStr to list", list2.toString());
注意和上边的简单类型略有不同。
参考 :
https://code.google.com/p/google-gson/
http://blog.csdn.net/lk_blog/article/details/7685169