GSON 簡單使用

RegPoate 8年前發布 | 8K 次閱讀 Java JSON

student類    

public class Student {  
    private int id;  
    private String name;  
    private Date birthDay;  

    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 Date getBirthDay() {  
        return birthDay;  
    }  

    public void setBirthDay(Date birthDay) {  
        this.birthDay = birthDay;  
    }  

    @Override  
    public String toString() {  
        return "Student [birthDay=" + birthDay + ", id=" + id + ", name="  
                + name + "]";  
    }  

}  

GsonTest1    

import java.util.ArrayList;  
import java.util.Date;  
import java.util.List;  

import com.google.gson.Gson;  
import com.google.gson.reflect.TypeToken;  

public class GsonTest1 {  

    public static void main(String[] args) {  
        Gson gson = new Gson();  

        Student student1 = new Student();  
        student1.setId(1);  
        student1.setName("李坤");  
        student1.setBirthDay(new Date());  

        // //////////////////////////////////////////////////////////  
        System.out.println("----------簡單對象之間的轉化-------------");  
        // 簡單的bean轉為json  
        String s1 = gson.toJson(student1);  
        System.out.println("簡單Bean轉化為Json===" + s1);  

        // json轉為簡單Bean  
        Student student = gson.fromJson(s1, Student.class);  
        System.out.println("Json轉為簡單Bean===" + student);  
        // 結果:  
        // 簡單Bean轉化為Json==={"id":1,"name":"李坤","birthDay":"Jun 22, 2012 8:27:52 AM"}  
        // Json轉為簡單Bean===Student [birthDay=Fri Jun 22 08:27:52 CST 2012, id=1,  
        // name=李坤]  
        // //////////////////////////////////////////////////////////  

        Student student2 = new Student();  
        student2.setId(2);  
        student2.setName("曹貴生");  
        student2.setBirthDay(new Date());  

        Student student3 = new Student();  
        student3.setId(3);  
        student3.setName("柳波");  
        student3.setBirthDay(new Date());  

        List<Student> list = new ArrayList<Student>();  
        list.add(student1);  
        list.add(student2);  
        list.add(student3);  

        System.out.println("----------帶泛型的List之間的轉化-------------");  
        // 帶泛型的list轉化為json  
        String s2 = gson.toJson(list);  
        System.out.println("帶泛型的list轉化為json==" + s2);  

        // json轉為帶泛型的list  
        List<Student> retList = gson.fromJson(s2,  
                new TypeToken<List<Student>>() {  
                }.getType());  
        for (Student stu : retList) {  
            System.out.println(stu);  
        }  

        // 結果:  
        // 帶泛型的list轉化為json==[{"id":1,"name":"李坤","birthDay":"Jun 22, 2012 8:28:52 AM"},{"id":2,"name":"曹貴生","birthDay":"Jun 22, 2012 8:28:52 AM"},{"id":3,"name":"柳波","birthDay":"Jun 22, 2012 8:28:52 AM"}]  
        // Student [birthDay=Fri Jun 22 08:28:52 CST 2012, id=1, name=李坤]  
        // Student [birthDay=Fri Jun 22 08:28:52 CST 2012, id=2, name=曹貴生]  
        // Student [birthDay=Fri Jun 22 08:28:52 CST 2012, id=3, name=柳波]  

    }  
}  

[代碼]Gson自定義適配器:TimestampAdapter     

package com.gdsc.core.adapter;  

import java.lang.reflect.Type;  
import java.sql.Timestamp;  

import com.google.gson.JsonDeserializationContext;  
import com.google.gson.JsonDeserializer;  
import com.google.gson.JsonElement;  
import com.google.gson.JsonParseException;  
import com.google.gson.JsonPrimitive;  
import com.google.gson.JsonSerializationContext;  
import com.google.gson.JsonSerializer;  

/** 
 * Gson TypeAdapter 
 * 實現了 Timestamp 類的 json 化 
 * @author linwei 
 * 
 */  
public class TimestampAdapter implements JsonSerializer<Timestamp>, JsonDeserializer<Timestamp> {  

    @Override  
    public Timestamp deserialize(JsonElement json, Type typeOfT,  
            JsonDeserializationContext context) throws JsonParseException {  
        if(json == null){  
            return null;  
        } else {  
            try {  
                return new Timestamp(json.getAsLong());  
            } catch (Exception e) {  
                return null;  
            }  
        }  
    }  

    @Override  
    public JsonElement serialize(Timestamp src, Type typeOfSrc,  
            JsonSerializationContext context) {  
        String value = "";  
        if(src != null){  
            value = String.valueOf(src.getTime());  
        }  
        return new JsonPrimitive(value);  
    }  

}  

[代碼]注冊類型適配器    

Gson gson = new GsonBuilder()  
                    .registerTypeAdapter(Timestamp.class, new TimestampAdapter())  
                    .create();  
 本文由用戶 RegPoate 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!