1、Gson是什么?
Gson 是 Google 提供的用来在 Java 对象和 JSON 数据之间进行映射的 Java 类库
2、有什么用?
序列化java对象为 JSON字符串,或反序列化JSON字符串成java对象;
可以将一个 JSON 字符串转成一个 Java 对象,或者反过来
3、怎么用?
(1)下载Gson2.3.1,下载地址https://code.google.com/p/google-gson/。下面有一系列的文档资源,如API,英文教程(地址:https://sites.google.com/site/gson/gson-user-guide)。
导入Gson的jar包,即做好准备工作。
-使用方法
来源:http://zh.wikipedia.org/wiki/Gson
Gson的应用主要为toJson与fromJson两个转换函数,而在使用这种对象转换之前需先创建好对象的类以及其成员才能成功的将JSON字符串成功转换成相对应的对象。
例子:
public class Student
{
private int answer1 ;
private String answer2 ;
//测试一个数组
private List employee = new ArrayList();
public List getEmployee()
{
return employee;
}
public int getAnswer1() {
return answer1;
}
public void setAnswer1(int answer1) {
this.answer1 = answer1;
}
public String getAnswer2() {
return answer2;
}
public void setAnswer2(String answers2) {
this.answer2 = answers2;
}
}
创建一个Emloyee类
class Employee
{
String firstName;
String LastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return LastName;
}
public void setLastName(String lastName) {
LastName = lastName;
}
public Employee(String firstName, String lastName) {
super();
this.firstName = firstName;
LastName = lastName;
}
}
测试toJson方法,得到Json字符串
public static void main(String[] args) {
//新建对象
Student student1= new Student();
student1.setAnswer1( 100);
student1.setAnswer2("hello");
Employee employee1 =new Employee("John" , "Doe");
Employee employee2 =new Employee("Tom" , "Smith");
student1.getEmployee().add(employee1);
student1.getEmployee().add(employee2);
//创建Gson类对象
Gson gson = new Gson();
//调用方法,将一般对象转化为json格式的字符串
String json = gson.toJson(student1);
System.out.println(json);
}
输出Json格式字符串
{"answer1":100,"answer2":"hello","employee":[{"firstName":"John","LastName":"Doe"},{"firstName":"Tom","LastName":"Smith"}]}
-------------------------
将Json格式字符串转为java对象
Student student2 = new Student();
student2 = gson.fromJson(json,Student.class);
//重写Student类中的toString方法,用于打印
System.out.println(student2);
student1与student2是完全一样的;
---------------------