IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 开发测试 -> Google Gson -> 正文阅读

[开发测试]Google Gson

一、Gson介绍


什么是Gson

Gson是Google开发的Java API,是一个简单的基于Java的开源库,用于转换Java对象和Json

Gson的特点

  • 易于使用?? ??? ?:Gson API提供了一个高级外观来简化常用的用例
  • 无须创建映射 :Gson API为大部分要序列化的对象提供了默认映射
  • 性能优?? ??? ??? ?:Gson速度较快,内存占用量低。
  • 无依赖性?? ??? ?:Gson不需要JDK以外的其他库

二、Maven 依赖


<dependency>
  <groupId>com.google.code.gson</groupId>
  <artifactId>gson</artifactId>
  <version>2.8.6</version>
</dependency>

三、序列化和反序列化


import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import lombok.Data;
import org.junit.Test;
import java.util.*;

public class GsonTest {
    //测试的实体类
    @Data
    public class TestEntity {
        private String name;
        private int age;
        private String sex;
        private Date birthday;
        private String email;
        private String address;

        public TestEntity() {}

        public TestEntity(String name, int age, String sex, Date birthday, String email, String address) {
            this.name = name;
            this.age = age;
            this.sex = sex;
            this.birthday = birthday;
            this.email = email;
            this.address = address;
        }
    }
    @Test
    public void gsonTset()  {
        //声明Gson对象
        Gson gson = new Gson();
        //声明Java对象,用于序列化
        TestEntity entity  = new TestEntity("盛夏 ",23,"未知",new Date(),"sx @xx.com",null);
        TestEntity entity1 = new TestEntity("盛夏1",23,"未知",new Date(),"sx1@xx.com",null);
        TestEntity entity2 = new TestEntity("盛夏2",23,"未知",new Date(),"sx2@xx.com",null);
        //序列化方法 toJson || 反序列化方法 fromJson


        /*-------序列化 对象 转化为 Json 字符串  -------*/
        String objectToJson = gson.toJson(entity);
        System.out.println(objectToJson);
        //{"name":"盛夏","age":23,"sex":"未知","birthday":"Apr 26, 2022 11:20:09 AM","email":"sx@xx.com"}
        /*-------反序列化 Json 转化为 Java 对象  -------*/
        TestEntity jsonToObject = gson.fromJson(objectToJson, TestEntity.class);
        System.out.println(jsonToObject);
        //GsonTest.TestEntity(name=盛夏 , age=23, sex=未知, birthday=Tue Apr 26 11:34:06 CST 2022, email=sx @xx.com, address=null)


        /*-------序列化 Map 转化为 Json 字符串  -------*/
        Map map = new HashMap();
        map.put("entity1",entity1);
        map.put("entity2",entity2);
        String mapToJson = gson.toJson(map);
        System.out.println(mapToJson);
        //{"entity1":{"name":"盛夏1","age":23,"sex":"未知","birthday":"Apr 26, 2022 11:28:49 AM","email":"sx1@xx.com"},
        // "entity2":{"name":"盛夏2","age":23,"sex":"未知","birthday":"Apr 26, 2022 11:28:49 AM","email":"sx2@xx.com"}}
        /*-------反序列化 Json 转化为 Map 集合  -------*/
        Map jsonToMap = gson.fromJson(mapToJson, new TypeToken<Map<String, TestEntity>>() {}.getType());
        System.out.println(jsonToMap);
        //{entity1=GsonTest.TestEntity(name=盛夏1, age=23, sex=未知, birthday=Tue Apr 26 11:38:38 CST 2022, email=sx1@xx.com, address=null),
        // entity2=GsonTest.TestEntity(name=盛夏2, age=23, sex=未知, birthday=Tue Apr 26 11:38:38 CST 2022, email=sx2@xx.com, address=null)}


        /*-------序列化 List 转化为 Json 字符串  -------*/
        List list = new ArrayList();
        list.add(entity1);
        list.add(entity2);
        String listToJson = gson.toJson(list);
        System.out.println(listToJson);
        //[{"name":"盛夏1","age":23,"sex":"未知","birthday":"Apr 26, 2022 11:31:37 AM","email":"sx1@xx.com"},
        // {"name":"盛夏2","age":23,"sex":"未知","birthday":"Apr 26, 2022 11:31:37 AM","email":"sx2@xx.com"}]
        /*-------反序列化 Json 转化为 List 集合  -------*/
        List jsonToList = gson.fromJson(listToJson, new TypeToken<List<TestEntity>>() {}.getType());
        System.out.println(jsonToList);
        // [GsonTest.TestEntity(name=盛夏1, age=23, sex=未知, birthday=Tue Apr 26 11:41:01 CST 2022, email=sx1@xx.com, address=null),
        //  GsonTest.TestEntity(name=盛夏2, age=23, sex=未知, birthday=Tue Apr 26 11:41:01 CST 2022, email=sx2@xx.com, address=null)]
    }



}

四、常用注解


1、@SerializedName注解 用于序列化和反序列化 字段取别名

package xxxxxxxxxx;
import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;
import com.google.gson.reflect.TypeToken;
import lombok.Data;
import org.junit.Test;
import java.util.*;

public class GsonTest {
    //测试的实体类
    @Data
    public class TestEntity {
        /*---注解SerializedName使用---*/
        // value = "userName" 给实体类字段取别名 ; name --> userName
        // alternate = {"alterName","uName"} 可用于反序列化,{"alterName","uName"}都可给name赋值
        @SerializedName(value = "userName",alternate = {"alterName","uName"})
        private String name;

        private int age;
        private String sex;
        private Date birthday;
        private String email;
        private String address;

        public TestEntity() {}

        public TestEntity(String name, int age, String sex, Date birthday, String email, String address) {
            this.name = name;
            this.age = age;
            this.sex = sex;
            this.birthday = birthday;
            this.email = email;
            this.address = address;
        }
    }
    @Test
    public void gsonTset()  {
        //声明Gson对象
        Gson gson = new Gson();
        //声明Java对象,用于序列化
        TestEntity entity  = new TestEntity("盛夏 ",23,"未知",new Date(),"sx @xx.com",null);
        
        // name 序列化为 userName
        String toJson = gson.toJson(entity);
        System.out.println(toJson);
        //{"userName":"盛夏 ","age":23,"sex":"未知","birthday":"Apr 27, 2022 5:15:57 PM","email":"sx @xx.com"}

        // 用 name 反序列化来给 name 赋值 ;会出现赋值不上
        String nameJsonToObject = "{\"name\":\"盛夏 \",\"age\":23,\"sex\":\"未知\",\"birthday\":\"Apr 27, 2022 5:15:57 PM\",\"email\":\"sx @xx.com\"}";
        TestEntity entity1 = gson.fromJson(nameJsonToObject, TestEntity.class);
        System.out.println(entity1);
        //GsonTest.TestEntity(name=null, age=23, sex=未知, birthday=Wed Apr 27 17:15:57 CST 2022, email=sx @xx.com, address=null)

        // 用 alterName 反序列化来给 name 赋值 ,可赋值成功
        String alterNameJsonToObject = "{\"alterName\":\"盛夏 \",\"age\":23,\"sex\":\"未知\",\"birthday\":\"Apr 27, 2022 5:15:57 PM\",\"email\":\"sx @xx.com\"}";
        TestEntity entity2 = gson.fromJson(alterNameJsonToObject, TestEntity.class);
        System.out.println(entity2);
        //GsonTest.TestEntity(name=盛夏 , age=23, sex=未知, birthday=Wed Apr 27 17:15:57 CST 2022, email=sx @xx.com, address=null)

        // 用 uName 反序列化来给 name 赋值 ,可赋值成功
        String uNameJsonToObject = "{\"uName\":\"盛夏 \",\"age\":23,\"sex\":\"未知\",\"birthday\":\"Apr 27, 2022 5:15:57 PM\",\"email\":\"sx @xx.com\"}";
        TestEntity entity3 = gson.fromJson(uNameJsonToObject, TestEntity.class);
        System.out.println(entity3);
        //GsonTest.TestEntity(name=盛夏 , age=23, sex=未知, birthday=Wed Apr 27 17:15:57 CST 2022, email=sx @xx.com, address=null)


        // 用 userName 反序列化来给 name 赋值 ,可赋值成功
        String newJsonToObject = toJson ;
        TestEntity entity4 = gson.fromJson(newJsonToObject, TestEntity.class);
        System.out.println(entity4);
        //GsonTest.TestEntity(name=盛夏 , age=23, sex=未知, birthday=Wed Apr 27 17:20:11 CST 2022, email=sx @xx.com, address=null)
    }

}

2、@Expose注解 是否序列化和反序列化【注意Gson声明和不加注解情况】

package com.xinsteel.finance;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import com.google.gson.reflect.TypeToken;
import lombok.Data;
import org.apache.poi.ss.formula.functions.T;
import org.junit.Test;
import java.util.*;


public class GsonTest {
    //测试的实体类
    @Data
    public class TestEntity {
        /*---Expose ---*/
        // @Expose(serialize=true) : 序列化的时候是否 序列化该字段 【true:序列化 ;false:不序列化】
        // @Expose(deserialize=true) : 反序列化的时候是否 反序列化该字段 【true:反序列化 ;false:不反序列化】
        @Expose(serialize = true)
        private String name;

        @Expose(deserialize = true)
        private int age;

        @Expose(serialize = false)
        private String sex;

        @Expose(deserialize = false)
        private Date birthday;

        // 不加 @Expose 注解 等于 @Expose(serialize = false , deserialize = false)
        private String email;
        
        private String address;

        public TestEntity() {}

        public TestEntity(String name, int age, String sex, Date birthday, String email, String address) {
            this.name = name;
            this.age = age;
            this.sex = sex;
            this.birthday = birthday;
            this.email = email;
            this.address = address;
        }
    }
    @Test
    public void gsonTset()  {
        //声明Gson对象
        Gson gson = new Gson();

        //声明Gson对象
        Gson buildGson  = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();

        //声明Java对象,用于序列化
        TestEntity entity  = new TestEntity("盛夏 ",23,"未知",new Date(),"sx @xx.com",null);

        // 用 gson 序列化 会毫无反映
        String objectToJson = gson.toJson(entity);
        System.out.println(objectToJson);
        // {"name":"盛夏 ","age":23,"sex":"未知","birthday":"Apr 27, 2022 5:42:21 PM","email":"sx @xx.com"}

        // 用 buildGson 序列化
        String objectToBuildJson = buildGson.toJson(entity);
        // name 字段会被序列化 ;sex 字段不会被序列化
        System.out.println(objectToBuildJson);
        //{"name":"盛夏 ","age":23,"birthday":"Apr 27, 2022 5:47:20 PM"}

        // 用 buildGson 反序列化
        TestEntity buildEntity = buildGson.fromJson(objectToBuildJson, TestEntity.class);
        // age字段 会被反序列化 ; birthday字段 不会被序列化
        System.out.println(buildEntity);
        //GsonTest.TestEntity(name=盛夏 , age=23, sex=null, birthday=null, email=null, address=null)
    }
}

三、@Since(double v)?与?@Until(double v) 注解 【版本控制】

Emm

四、@JsonAdapter?注解 【一般用于时间转换】

Emm 不咋会用

package com.xinsteel.finance;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import com.nisco.common.core.util.DateUtil;
import lombok.Data;
import lombok.SneakyThrows;
import org.apache.poi.ss.formula.functions.T;
import org.junit.Test;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

public class GsonTest {
    //测试的实体类
    @Data
    public class TestEntity {

        private String name;


        private int age;


        private String sex;

        // 这注解不咋会用 参数是个类 这个类要继承TypeAdapter,重写read和write方法,用于序列化和反序列化
        @JsonAdapter(FormatDate.class)
        private Date birthday;


        private String email;

        private String address;

        public TestEntity() {}

        public TestEntity(String name, int age, String sex, Date birthday, String email, String address) {
            this.name = name;
            this.age = age;
            this.sex = sex;
            this.birthday = birthday;
            this.email = email;
            this.address = address;
        }
    }
    @Test
    public void gsonTset()  {
        //声明Gson对象
        Gson gson = new Gson();


        //声明Java对象,用于序列化
        TestEntity entity  = new TestEntity("盛夏 ",23,"未知",new Date(),"sx @xx.com",null);

        
        String objectToJson = gson.toJson(entity);
        System.out.println(objectToJson);
        //{"name":"盛夏 ","age":23,"sex":"未知","birthday":2022-04-27-18-25-16,"email":"sx @xx.com"}

        TestEntity entity1 = gson.fromJson(objectToJson, entity.getClass());
        System.out.println(entity1);
        //GsonTest.TestEntity(name=盛夏 , age=23, sex=未知, birthday=Wed Apr 27 18:25:16 CST 2022, email=sx @xx.com, address=null)


    }

    class FormatDate extends TypeAdapter {
        public static final String DATE_FORMAT_DASH_TIME = "yyyy-MM-dd-HH-mm-ss"; // 对格式化有要求,不太会用

        public  FormatDate(){ }

        @Override
        public void write(JsonWriter out, Object value) throws IOException {
            if (value == null) {
                out.nullValue();
            } else {
                out.jsonValue(new SimpleDateFormat(DATE_FORMAT_DASH_TIME).format(value));
            }
        }

        @SneakyThrows
        @Override
        public Object read(JsonReader in) throws IOException {
            return new SimpleDateFormat(DATE_FORMAT_DASH_TIME,Locale.CHINA).parse(in.nextString());
        }
    }
}

  开发测试 最新文章
pytest系列——allure之生成测试报告(Wind
某大厂软件测试岗一面笔试题+二面问答题面试
iperf 学习笔记
关于Python中使用selenium八大定位方法
【软件测试】为什么提升不了?8年测试总结再
软件测试复习
PHP笔记-Smarty模板引擎的使用
C++Test使用入门
【Java】单元测试
Net core 3.x 获取客户端地址
上一篇文章      下一篇文章      查看所有文章
加:2022-04-30 09:00:00  更:2022-04-30 09:00:09 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年5日历 -2024/5/19 10:55:51-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码