Java学习者论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

手机号码,快捷登录

恭喜Java学习者论坛(https://www.javaxxz.com)已经为数万Java学习者服务超过8年了!积累会员资料超过10000G+
成为本站VIP会员,下载本站10000G+会员资源,购买链接:点击进入购买VIP会员
JAVA高级面试进阶视频教程Java架构师系统进阶VIP课程

分布式高可用全栈开发微服务教程

Go语言视频零基础入门到精通

Java架构师3期(课件+源码)

Java开发全终端实战租房项目视频教程

SpringBoot2.X入门到高级使用教程

大数据培训第六期全套视频教程

深度学习(CNN RNN GAN)算法原理

Java亿级流量电商系统视频教程

互联网架构师视频教程

年薪50万Spark2.0从入门到精通

年薪50万!人工智能学习路线教程

年薪50万!大数据从入门到精通学习路线年薪50万!机器学习入门到精通视频教程
仿小米商城类app和小程序视频教程深度学习数据分析基础到实战最新黑马javaEE2.1就业课程从 0到JVM实战高手教程 MySQL入门到精通教程
查看: 285|回复: 0

[默认分类] Google Gson 使用简介

[复制链接]
  • TA的每日心情
    开心
    2021-12-13 21:45
  • 签到天数: 15 天

    [LV.4]偶尔看看III

    发表于 2018-5-23 15:55:19 | 显示全部楼层 |阅读模式

    如何将数组转化为 json 串?

    下面的例子中我们示例如何将一个数据转换成 json 串,并使用
    1. Gson.toJson()
    复制代码
    方法将数组序列化为 JSON,以及
    1. Gson.fromJson()
    复制代码
    方法将 JSON 串反序列化为 java 数组。

    1. import com.google.gson.Gson;
    2. public class ArrayToJson {
    3.     public static void main(String[] args) {
    4.         int[] numbers = {1, 1, 2, 3, 5, 8, 13};
    5.         String[] days = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
    6.         //
    7.         // Create a new instance of Gson
    8.         //
    9.         Gson gson = new Gson();
    10.         //
    11.         // Convert numbers array into JSON string.
    12.         //
    13.         String numbersJson = gson.toJson(numbers);
    14.         //
    15.         // Convert strings array into JSON string
    16.         //
    17.         String daysJson = gson.toJson(days);
    18.         System.out.println("numbersJson = " + numbersJson);
    19.         System.out.println("daysJson = " + daysJson);
    20.         //
    21.         // Convert from JSON string to a primitive array of int.
    22.         //
    23.         int[] fibonacci = gson.fromJson(numbersJson, int[].class);
    24.         for (int i = 0; i < fibonacci.length; i++) {
    25.             System.out.print(fibonacci[i] + " ");
    26.         }
    27.         System.out.println("");
    28.         //
    29.         // Convert from JSON string to a string array.
    30.         //
    31.         String[] weekDays = gson.fromJson(daysJson, String[].class);
    32.         for (int i = 0; i < weekDays.length; i++) {
    33.             System.out.print(weekDays[i] + " ");
    34.         }
    35.         System.out.println("");
    36.         //
    37.         // Converting multidimensional array into JSON
    38.         //
    39.         int[][] data = {{1, 2, 3}, {3, 4, 5}, {4, 5, 6}};
    40.         String json = gson.toJson(data);
    41.         System.out.println("Data = " + json);
    42.         //
    43.         // Convert JSON string into multidimensional array of int.
    44.         //
    45.         int[][] dataMap = gson.fromJson(json, int[][].class);
    46.         for (int i = 0; i < data.length; i++) {
    47.             for (int j = 0; j < data[i].length; j++) {
    48.                 System.out.print(data[i][j] + " ");
    49.             }
    50.             System.out.println("");
    51.         }
    52.     }
    53. }
    复制代码


    以下是输出结果:

    1. numbersJson = [1,1,2,3,5,8,13]
    2. daysJson = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"]
    3. 1 1 2 3 5 8 13
    4. Sun Mon Tue Wed Thu Fri Sat
    5. Data = [[1,2,3],[3,4,5],[4,5,6]]
    6. 1 2 3
    7. 3 4 5
    复制代码


      

    如何将集合转化为 json 串?

    下面的例子中我们示例如何将Java集合转换为符合 json 规则的字符串。

    1. import java.util.Date;
    2. public class Student {
    3.     private String name;
    4.     private String address;
    5.     private Date dateOfBirth;
    6.     public Student() {
    7.     }
    8.     public Student(String name, String address, Date dateOfBirth) {
    9.         this.name = name;
    10.         this.address = address;
    11.         this.dateOfBirth = dateOfBirth;
    12.     }
    13.     public String getName() {
    14.         return name;
    15.     }
    16.     public void setName(String name) {
    17.         this.name = name;
    18.     }
    19.     public String getAddress() {
    20.         return address;
    21.     }
    22.     public void setAddress(String address) {
    23.         this.address = address;
    24.     }
    25.     public Date getDateOfBirth() {
    26.         return dateOfBirth;
    27.     }
    28.     public void setDateOfBirth(Date dateOfBirth) {
    29.         this.dateOfBirth = dateOfBirth;
    30.     }
    31. }
    复制代码



    1. import com.google.gson.Gson;
    2. import com.google.gson.reflect.TypeToken;
    3. import java.lang.reflect.Type;
    4. import java.util.ArrayList;
    5. import java.util.Date;
    6. import java.util.List;
    7. public class CollectionToJson {
    8.     public static void main(String[] args) {
    9.         //
    10.         // Converts a collection of string object into JSON string.
    11.         //
    12.         List<String> names = new ArrayList<String>();
    13.         names.add("Alice");
    14.         names.add("Bob");
    15.         names.add("Carol");
    16.         names.add("Mallory");
    17.         Gson gson = new Gson();
    18.         String jsonNames = gson.toJson(names);
    19.         System.out.println("jsonNames = " + jsonNames);
    20.         //
    21.         // Converts a collection Student object into JSON string
    22.         //
    23.         Student a = new Student("Alice", "Apple St", new Date(2000, 10, 1));
    24.         Student b = new Student("Bob", "Banana St", null);
    25.         Student c = new Student("Carol", "Grape St", new Date(2000, 5, 21));
    26.         Student d = new Student("Mallory", "Mango St", null);
    27.         List<Student> students = new ArrayList<Student>();
    28.         students.add(a);
    29.         students.add(b);
    30.         students.add(c);
    31.         students.add(d);
    32.         gson = new Gson();
    33.         String jsonStudents = gson.toJson(students);
    34.         System.out.println("jsonStudents = " + jsonStudents);
    35.         //
    36.         // Converts JSON string into a collection of Student object.
    37.         //
    38.         Type type = new TypeToken<List<Student>>(){}.getType();
    39.         List<Student> studentList = gson.fromJson(jsonStudents, type);
    40.         for (Student student : studentList) {
    41.             System.out.println("student.getName() = " + student.getName());
    42.         }
    43.     }
    44. }
    复制代码


    以下是输出结果:

    1. jsonNames = ["Alice","Bob","Carol","Mallory"]
    2. jsonStudents = [{"name":"Alice","address":"Apple St","dateOfBirth":"Nov 1, 3900 12:00:00 AM"},{"name":"Bob","address":"Banana St"},{"name":"Carol","address":"Grape St","dateOfBirth":"Jun 21, 3900 12:00:00 AM"},{"name":"Mallory","address":"Mango St"}]
    3. student.getName() = Alice
    4. student.getName() = Bob
    5. student.getName() = Carol
    6. student.getName() = Mallory
    复制代码


      

    如何将Map转化为 json 串?

    下面的例子中我们示例如何将
    1. java.util.Map
    复制代码
    转化成 json 串,然后再将 json 串转换为
    1. java.util.Map
    复制代码


    1. import com.google.gson.Gson;
    2. import com.google.gson.reflect.TypeToken;
    3. import java.lang.reflect.Type;
    4. import java.util.HashMap;
    5. import java.util.Map;
    6. public class MapToJson {
    7.     public static void main(String[] args) {
    8.         Map<String, String> colours = new HashMap<String, String>();
    9.         colours.put("BLACK", "#000000");
    10.         colours.put("RED", "#FF0000");
    11.         colours.put("GREEN", "#008000");
    12.         colours.put("BLUE", "#0000FF");
    13.         colours.put("YELLOW", "#FFFF00");
    14.         colours.put("WHITE", "#FFFFFF");
    15.         //
    16.         // Convert a Map into JSON string.
    17.         //
    18.         Gson gson = new Gson();
    19.         String json = gson.toJson(colours);
    20.         System.out.println("json = " + json);
    21.         //
    22.         // Convert JSON string back to Map.
    23.         //
    24.         Type type = new TypeToken<Map<String, String>>(){}.getType();
    25.         Map<String, String> map = gson.fromJson(json, type);
    26.         for (String key : map.keySet()) {
    27.             System.out.println("map.get = " + map.get(key));
    28.         }
    29.     }
    30. }
    复制代码


    以下是输出结果:

    1. json = {"WHITE":"#FFFFFF","BLUE":"#0000FF","YELLOW":"#FFFF00","GREEN":"#008000","BLACK":"#000000","RED":"#FF0000"}
    2. map.get = #FFFFFF
    3. map.get = #0000FF
    4. map.get = #FFFF00
    5. map.get = #008000
    6. map.get = #000000
    7. map.get = #FF0000
    复制代码


      

    如何将对象转换为 json 串?

    下面的例子中我们示例如何将一个 Student 对象转换成 json 串,实际操作中我们也可以将任意的 Java 类转换为 json 串,并且实施起来也非常简单,你仅仅需要创建一个 Gson 实例,然后传递将被转化为 json 串的对象,并调用该实例的 toJson 方法即可。

    1. import com.google.gson.Gson;
    2. import java.util.Calendar;
    3. public class StudentToJson {
    4.     public static void main(String[] args) {
    5.         Calendar dob = Calendar.getInstance();
    6.         dob.set(2000, 1, 1, 0, 0, 0);
    7.         Student student = new Student("Duke", "Menlo Park", dob.getTime());
    8.         Gson gson = new Gson();
    9.         String json = gson.toJson(student);
    10.         System.out.println("json = " + json);
    11.     }
    12. }
    复制代码



    1. import java.util.Date;
    2. public class Student {
    3.     private String name;
    4.     private String address;
    5.     private Date dateOfBirth;
    6.     public Student() {
    7.     }
    8.     public Student(String name, String address, Date dateOfBirth) {
    9.         this.name = name;
    10.         this.address = address;
    11.         this.dateOfBirth = dateOfBirth;
    12.     }
    13.     public String getName() {
    14.         return name;
    15.     }
    16.     public void setName(String name) {
    17.         this.name = name;
    18.     }
    19.     public String getAddress() {
    20.         return address;
    21.     }
    22.     public void setAddress(String address) {
    23.         this.address = address;
    24.     }
    25.     public Date getDateOfBirth() {
    26.         return dateOfBirth;
    27.     }
    28.     public void setDateOfBirth(Date dateOfBirth) {
    29.         this.dateOfBirth = dateOfBirth;
    30.     }
    31. }
    复制代码


    以下是输出结果:

    1. json = {"name":"Duke","address":"Menlo Park","dateOfBirth":"Feb 1, 2000 12:00:00 AM"}
    复制代码


      

    如何将 json 串转换为对象?

    下面的例子中我们示例如何 json 串转化成 Java对象。

    1. import com.google.gson.Gson;
    2. public class JsonToStudent {
    3.     public static void main(String[] args) {
    4.         String json = "{"name":"Duke","address":"Menlo Park","dateOfBirth":"Feb 1, 2000 12:00:00 AM"}";
    5.         Gson gson = new Gson();
    6.         Student student = gson.fromJson(json, Student.class);
    7.         System.out.println("student.getName()        = " + student.getName());
    8.         System.out.println("student.getAddress()     = " + student.getAddress());
    9.         System.out.println("student.getDateOfBirth() = " + student.getDateOfBirth());
    10.     }
    11. }
    复制代码


    以下是输出结果:

    1. student.getName()        = Duke
    2. student.getAddress()     = Menlo Park
    3. student.getDateOfBirth() = Tue Feb 01 00:00:00 CST 2000
    复制代码


      

    如何处理对象的字段?

    下面的例子中我们示例如何利用Gson处理一个对象的某一字段。

    1. import com.google.gson.Gson;
    2. import java.util.Calendar;
    3. public class GsonFieldExample {
    4.     public static void main(String[] args) {
    5.         Calendar dob = Calendar.getInstance();
    6.         dob.set(1980, 10, 11);
    7.         People people = new People("John", "350 Banana St.", dob.getTime());
    8.         people.setSecret("This is a secret!");
    9.         Gson gson = new Gson();
    10.         String json = gson.toJson(people);
    11.         System.out.println("json = " + json);
    12.     }
    13. }
    复制代码



    1. import java.util.Date;
    2. public class People {
    3.     private String name;
    4.     private String address;
    5.     private Date dateOfBirth;
    6.     private Integer age;
    7.     private transient String secret;
    8.     public People(String name, String address, Date dateOfBirth) {
    9.         this.name = name;
    10.         this.address = address;
    11.         this.dateOfBirth = dateOfBirth;
    12.     }
    13.     public String getSecret() {
    14.         return secret;
    15.     }
    16.     public void setSecret(String secret) {
    17.         this.secret = secret;
    18.     }
    19. }
    复制代码


    以下是输出结果:

    1. json = {"name":"John","address":"350 Banana St.","dateOfBirth":"Nov 11, 1980 8:47:04 AM"}
    复制代码

    回复

    使用道具 举报

    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    QQ|手机版|Java学习者论坛 ( 声明:本站资料整理自互联网,用于Java学习者交流学习使用,对资料版权不负任何法律责任,若有侵权请及时联系客服屏蔽删除 )

    GMT+8, 2024-5-16 19:54 , Processed in 0.455008 second(s), 47 queries .

    Powered by Discuz! X3.4

    © 2001-2017 Comsenz Inc.

    快速回复 返回顶部 返回列表