关于gson的解析

来源:互联网 发布:linux内核进程调度 编辑:程序博客网 时间:2024/05/01 14:59

Gson是Google提供的方便在json数据和Java对象之间转化的类库。        Gson地址


Gson

这是使用Gson的主要类,使用它时一般先创建一个Gson实例,然后调用toJson(Object)或者from(String,Class)方法进行转换。


[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. package com.example.gson;  
  2.   
  3. import com.google.gson.annotations.Expose;  
  4. import com.google.gson.annotations.SerializedName;  
  5.   
  6. import java.util.Date;  
  7.   
  8. /** 
  9.  * Student 实体类 
  10.  * Created by liu on 13-11-25. 
  11.  */  
  12. public class Student {  
  13.     int age;  
  14.     String name;  
  15.     @Expose(serialize = true,deserialize = false)  
  16.     @SerializedName("bir")  
  17.     Date birthday;  
  18.   
  19.     public Student(int age, String name, Date birthday) {  
  20.         this.age = age;  
  21.         this.name = name;  
  22.         this.birthday = birthday;  
  23.     }  
  24.   
  25.     public Student(int age, String name) {  
  26.         this.age = age;  
  27.         this.name = name;  
  28.     }  
  29.   
  30.   
  31.     @Override  
  32.     public String toString() {  
  33.         if (birthday == null) {  
  34.             return "{\"name\":" + name + ", \"age\":" + age + "}";  
  35.         } else {  
  36.             return "{\"name\":" + name + ", \"age\":" + age + ", \"birthday\":" + birthday.toString() + "}";  
  37.         }  
  38.   
  39.     }  
  40. }  


使用Gson前先创建Gson对象。

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. //首先创建Gson实例  
  2.        Gson gson = new Gson();  

1.   toJson,fromJson 简单对象之间的转化


[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. Student student = new Student(11"liupan");  
  2.       String jsonStr = gson.toJson(student, Student.class);  
  3.       Log.e("Object to jsonStr", jsonStr);  
  4.   
  5.       Student student1 = gson.fromJson(jsonStr, Student.class);  
  6.       Log.e("jsonStr to Object", student1.toString());  

2    List 类型和JSON字符串之间的转换

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. Student student11 = new Student(11"liupan11");  
  2.        Student student12 = new Student(12"liupan12");  
  3.        Student student13 = new Student(13"liupan13");  
  4.        Stack<Student> list = new Stack<Student>();  
  5.        list.add(student11);  
  6.        list.add(student12);  
  7.        list.add(student13);  

toJson
[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. String listJsonStr = gson.toJson(list);  
  2.        Log.e("list to jsonStr", listJsonStr);  

fromJson

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. Stack<Student> list2 = gson.fromJson(listJsonStr, new TypeToken<Stack<Student>>() {  
  2.      }.getType());  
  3.      Log.e("jsonStr to list", list2.toString());  
0 0