Day05Ajax中gson的詳細介紹

1.

gson的作用

在服務器端把java對象,集合轉化爲json字符串,傳遞給client(客戶端)
2.

gson的使用

a. 基礎場景

       Gson gson = new Gson();
       gson.toJson();

實例:

@Test
    public void test1() {
        User u = new User(1,"suns","123456");//json字符
        Gson gson = new Gson();
        String jsonString = gson.toJson(u);
        System.out.println(jsonString);
        //運行結果
        //{"id":1,"name":"suns","password":"123456"}
    }
    @Test
    public void test2() {
        String[] names = new String[]{"suns","huxz"};
        Gson gson = new Gson();
        String jsonString = gson.toJson(names);
        System.out.println(jsonString);
        //運行結果
        //["suns","huxz"]
    }

b. 複雜場景

       GsonBuilder gb = new GsonBuilder();
       Gson gson = gb.creat();
       gson.toJson();

gson轉換對象時 處理特殊類型的屬性(日期)

實體類

package com.ajax;

import java.util.Date;

public class Customer {
    private Integer id;
    private String name;
    private Date birthday;


    public Customer() {
        super();
    }
    public Customer(Integer id, String name, Date birthday) {
        super();
        this.id = id;
        this.name = name;
        this.birthday = birthday;
    }
    public Integer getId() {
        return id;
    }
    public void setId(Integer 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;
    }

}

Test1方法爲基礎類實現所面臨的問題

public class TestGsonSpecifical {
    @Test
    public void Test1(){
        Customer c = new Customer(1,"zhang",new java.util.Date());
        Gson gson = new Gson();
        String jsonString = gson.toJson(c);
        System.out.println(jsonString);
        /*運行結果{"id":1,"name":"zhang","birthday":"Jan 8, 2018 3:11:43 PM"} 日期格式問題
    }

以下爲解決Test1方法

方法一:
步驟1: 寫一個類把數據按照程序需求進行轉換

這裏寫圖片描述

代碼1:
轉換類
DateEditor.java

package com.ajax;

import java.lang.reflect.Type;
import java.text.SimpleDateFormat;

import com.google.gson.JsonElement;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

/*
 * 把日期轉換爲指定的格式
 */
public class DataEditor implements JsonSerializer{
    /*
     * 作用:把日期類型,轉換爲指定的字符串格式
     *     SimpleDateFormat  把java.util.Date  --- 指定格式的字符串
     * JsonElement:json中的一個元素
     */
    @Override
    public JsonElement serialize(Object date, Type arg1, JsonSerializationContext arg2) {
        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-DD");
        String dString = sd.format(date);

        return new JsonPrimitive(dString);//JsonPrimitive  8+基本類型
    }
}

步驟2:進行類型轉換器的註冊

這裏寫圖片描述

代碼2:

    @Test
    public void Test2(){
        Customer c = new Customer(2,"jie",new java.util.Date());
        GsonBuilder gb = new GsonBuilder();//要爲日期寫轉換類
        gb.registerTypeAdapter(Date.class, new DataEditor());//註冊date類型轉換器
        Gson gson = gb.create();
        String jsonString = gson.toJson(c);
        System.out.println(jsonString);
        /*運行結果{"id":2,"name":"jie","birthday":"2018-01-08"} */
    }
}

迴環問題你中有我,我中有你

Test2問題:
Customer{
id,
name,
birthday,
address Address;
}
Address{
id,
city,
zipcode,
customer Customer;
}
Customer 中有 City
City 中有 Customer
gson無法解析

兩種解決方法 核心:設置迴環策略

第一種解決方法
步驟一:寫一個類實現接口,書寫排除策略

這裏寫圖片描述
實例代碼1:

package com.ajax;

import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;

public class CustomerExcusion implements ExclusionStrategy{
    @Override
    //排除類
    public boolean shouldSkipClass(Class<?> arg0) {

        return false;
    }
    @Override
    //排除屬性(此處使用排除屬性)    
    public boolean shouldSkipField(FieldAttributes f) {
        //f.getName()獲取屬性名,如果屬性名等於customer,則返回true(過濾這個屬性,不再轉換),否則返回false
        if(f.getName().equals("customer")){
            return true;  //"customer"需要排除的屬性名,只有此處是變化的
        }
        return false;
    }
}

步驟二:排除策略的註冊

這裏寫圖片描述

示例代碼2:

@Test
    public void Test3(){//迴環問題,你中有我,我中有你
        Customer c = new Customer();
        c.setId(1);
        c.setName("zhang");
        c.setBirthday(new java.util.Date());

        Address a = new Address();
        a.setCity("bj");
        a.setId("1");
        a.setZipcode("100030");

        c.setAddress(a);
        a.setCustomer(c);

        /*Gson gson = new Gson();
        String jsonString = gson.toJson(c);
        System.out.println(c);//報錯,死循環
         */     
        GsonBuilder gb = new GsonBuilder();
        gb.setExclusionStrategies(new CustomerExcusion());//註冊排除策略
        Gson gson = gb.create();
        String jsonString = gson.toJson(c);
        System.out.println(jsonString);
        //{"id":1,"name":"zhang","birthday":"Mar 10, 2018 4:30:36 PM","address":{"id":"1","city":"bj","zipcode":"100030"}}
    }

第二種解決方法
基於註解(@expose) 不適合大範圍使用

步驟一:把需要轉換的屬性加入@expose註解
實例代碼1:

public class Customer {
    @Expose  //依賴註解,有註解的進行gson轉換,無註解的不進行轉換
    private Integer id;
    @Expose
    private String name;
    @Expose
    private Date birthday;
    @Expose
    private Address address;
    ……
}
public class Address {
    @Expose 
    private String id;
    @Expose
    private String city;
    @Expose
    private String zipcode;
    private Customer customer;
    ……
}

步驟二:應用GsonBuilder處理

這裏寫圖片描述

實例代碼:

@Test 
    public void Test3(){//迴環問題,你中有我,我中有你
        Customer c = new Customer();
        c.setId(1);
        c.setName("zhang");
        c.setBirthday(new java.util.Date());

        Address a = new Address();
        a.setCity("bj");
        a.setId("1");
        a.setZipcode("100030");

        c.setAddress(a);
        a.setCustomer(c);

        GsonBuilder gb = new GsonBuilder();
        gb.excludeFieldsWithoutExposeAnnotation();
        Gson gson = gb.create();
        String jsonString = gson.toJson(c);
        System.out.println(jsonString);
        //{"id":1,"name":"zhang","birthday":"Mar 10, 2018 5:06:29 PM","address":{"id":"1","city":"bj","zipcode":"100030"}}

    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章