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: 写一个类把数据按照程序需求进行转换

Day05Ajax中gson的详细介绍_第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无法解析

两种解决方法 核心:设置回环策略

第一种解决方法
步骤一:写一个类实现接口,书写排除策略

Day05Ajax中gson的详细介绍_第2张图片
实例代码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"}}

    }

你可能感兴趣的:(javaweb,ajax)