the latest version is 2.8.0. If you're using Gradle, add the following line:

compile 'com.google.code.gson:gson:2.8.0' 

If you're using Maven, you can add the following dependency:

<dependencies>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.0</version>
<scope>compile</scope>
</dependency>
</dependencie>

Primitives Examples

// Serialization
Gson gson = new Gson();
gson.toJson(1); // ==> 1
gson.toJson("abcd"); // ==> "abcd"
gson.toJson(new Long(10)); // ==> 10
int[] values = { 1 };
gson.toJson(values); // ==> [1] // Deserialization
int one = gson.fromJson("1", int.class);
Integer one = gson.fromJson("1", Integer.class);
Long one = gson.fromJson("1", Long.class);
Boolean false = gson.fromJson("false", Boolean.class);
String str = gson.fromJson("\"abc\"", String.class);
String[] anotherStr = gson.fromJson("[\"abc\"]", String[].class);

Object Examples

class BagOfPrimitives {
private int value1 = 1;
private String value2 = "abc";
private transient int value3 = 3;
BagOfPrimitives() {
// no-args constructor
}
} // Serialization
BagOfPrimitives obj = new BagOfPrimitives();
Gson gson = new Gson();
String json = gson.toJson(obj); // ==> json is {"value1":1,"value2":"abc"}

Note that you can not serialize objects with circular references since that will result in infinite recursion.

// Deserialization
BagOfPrimitives obj2 = gson.fromJson(json, BagOfPrimitives.class);
// ==> obj2 is just like obj

Nested Classes (including Inner Classes)

Gson can serialize static nested classes quite easily.

Gson can also deserialize static nested classes. However, Gson can not automatically deserialize the pure inner classes since their no-args constructor also need a reference to the containing Object which is not available at the time of deserialization. You can address this problem by either making the inner class static or by providing a custom InstanceCreator for it. Here is an example:

public class A {
public String a; class B { public String b; public B() {
// No args constructor for B
}
}
}

NOTE: The above class B can not (by default) be serialized with Gson.

Gson can not deserialize {"b":"abc"} into an instance of B since the class B is an inner class. If it was defined as static class B then Gson would have been able to deserialize the string. Another solution is to write a custom instance creator for B.

public class InstanceCreatorForB implements InstanceCreator<A.B> {
private final A a;
public InstanceCreatorForB(A a) {
this.a = a;
}
public A.B createInstance(Type type) {
return a.new B();
}
}

The above is possible, but not recommended.

Array Examples

Gson gson = new Gson();
int[] ints = {1, 2, 3, 4, 5};
String[] strings = {"abc", "def", "ghi"}; // Serialization
gson.toJson(ints); // ==> [1,2,3,4,5]
gson.toJson(strings); // ==> ["abc", "def", "ghi"] // Deserialization
int[] ints2 = gson.fromJson("[1,2,3,4,5]", int[].class);
// ==> ints2 will be same as ints

We also support multi-dimensional arrays, with arbitrarily complex element types.

Collections Examples

Gson gson = new Gson();
Collection<Integer> ints = Lists.immutableList(1,2,3,4,5); // Serialization
String json = gson.toJson(ints); // ==> json is [1,2,3,4,5] // Deserialization
Type collectionType = new TypeToken<Collection<Integer>>(){}.getType();
Collection<Integer> ints2 = gson.fromJson(json, collectionType);
// ==> ints2 is same as ints

gson/UserGuide.md at master · google/gson
https://github.com/google/gson/blob/master/UserGuide.md#TOC-Gson-Users

Gson — Getting Started with Java-JSON Serialization & Deserialization
https://futurestud.io/tutorials/gson-getting-started-with-java-json-serialization-deserialization

google/gson: A Java serialization/deserialization library that can convert Java Objects into JSON and back.
https://github.com/google/gson

Google Gson用法的更多相关文章

  1. Android网络之数据解析----使用Google Gson解析Json数据

    [声明] 欢迎转载,但请保留文章原始出处→_→ 生命壹号:http://www.cnblogs.com/smyhvae/ 文章来源:http://www.cnblogs.com/smyhvae/p/4 ...

  2. Java创建和解析Json数据方法(五)——Google Gson包的使用

    (五)Google Gson包的使用 1.简介 Gson包中,使用最多的是Gson类的toJson()和fromJson()方法:         ①toJson():将java对象转化为json数据 ...

  3. [转]Json转换神器之Google Gson的使用

    这几天,因为项目的需要,接触了Google的Gson库,发现这个东西很好用,遂记下简单的笔记,供以后参考.至于Gson是干什么的,有什么优点,请各位同学自行百度.话不多说,切入正题: 1. 下载Gso ...

  4. [转]使用 google gson 转换Timestamp或Date类型为JSON字符串.

    创建类型适配类: import java.lang.reflect.Type; import java.sql.Timestamp; import java.text.DateFormat; impo ...

  5. 使用 google gson 转换Timestamp或Date类型为JSON字符串.

    http://blog.csdn.net/z69183787/article/details/13016289 创建类型适配类: import java.lang.reflect.Type; impo ...

  6. Exception in thread “main” com.google.gson.JsonSyntaxException: java.lang.NumberFormatException: empty String

    String json="A valid json"; Job job = new Gson().fromJson(json, Job.class); Exception in t ...

  7. org.json.JSONObject与com.google.gson.Gson

    org.json库为JSON创始人编写的解析JSON的java库,Gson为Google为我们提供的解析JSON格式数据的库. Gson里最重要的对象有2个Gson 和GsonBuilder. Gso ...

  8. 使用 google gson 转换Timestamp为JSON字符串

    package com.test.base; import java.lang.reflect.Type; import java.sql.Timestamp; import java.text.Da ...

  9. Google Gson解析Json数据应用实例

    转自:http://lixigao449778967.blog.163.com/blog/static/24985164201269105928783/ 1.需要的Jar包 1) Google Gso ...

随机推荐

  1. python操作hive并且获取查询结果scheam

    执行hive -e 命令并且获取对应的select查询出来的值及其对应的scheam字段 需要在执行语句中前部添加 set hive.cli.print.header=true; 这个设置,如下语句: ...

  2. XSS攻击防御篇

    前言   上篇文章中提到了 XSS 攻击,而且,也从几个方面介绍了 XSS 攻击带来的严重影响.那么,这篇文章中,主要是针对 XSS 攻击做一个基本的防御,看看可以通过几种方式来修复这个特别常见的安全 ...

  3. 互评Beta版本(Hello World!——SkyHunter)

    1 基于NABCD评论作品,及改进建议 SkyHunter这款游戏我很喜欢,小时候总玩飞机类的游戏,这款游戏我上课的时候试玩了,在我电脑上运行是很好玩的,音乐震撼,画面玄幻,富有金属音乐的味道,游戏内 ...

  4. 冲刺One之站立会议7 /2015-5-20

    2015-5-20 在登陆成功之后要实现的是聊天界面的交互过程,不同的IP进行信息和数据的传递,这方面我们上学期Java实验里面有过相关的内容,我们把它拿过来改了一下格式,试着看能不能成功,目前还没实 ...

  5. 【流程图】购物车、三级菜单、sed替换

  6. SM2

    一.介绍 #百度 二.生成密钥对及证书 1.使用gmssl工具 详见gmssl 2.go 版本 详见https://github.com/tjfoc/gmsm 3.java版本 #尚未实现 1.初步使 ...

  7. 【奇奇怪怪的bug系列】微信小程序

    今天修改代码的时候,发现了一件让我很恐慌的事情,在app.json中修改页面路径顺序不起作用了: 这样我根本就看不到页面的效果啊??? 在折腾了半天后,才发现是一个比较乌龙的事情:昨天修改完首页后顺手 ...

  8. JAVA自学日记——Part Ⅰ.

    和C++比较相似,Java同样是面向对象的设计语言,在基础的语句上有一些不大的差别,经过两天的学习,大概的了解了在eclipse中如何进行简单的编程,解决一些简单的问题,诸如在学习C时做过的“字符串倒 ...

  9. [转帖]AMD、英特尔为何争相走向胶水多核处理器?真相在此

    AMD.英特尔为何争相走向胶水多核处理器?真相在此 胶水多核到底好不好?这个事不是简单一句话能说明的,今天的超能课堂里我们就来聊聊MCM胶水多核技术的过去及未来. 作者:孟宪瑞来源:超能网|2018- ...

  10. Oracle与SQLSERVER 批处理执行 DDL 语句

    1. 公司里面的 很多同名的数据库 的一个表都错误的多了一个列 要是每个都用数据库连接工具打开 感觉太废时间了. 比如写个sql命令来执行. 具体方法: Oracle 使用 sqlplus sqlpl ...