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. Codeforces1151E,F | 553Div2 | 瞎讲报告

    传送链接 E. Number of Components 当时思博了..一直在想对于\([1,r]\)的联通块和\([1,l-1]\)的联通块推到\([l,r]\)的联通块...我真的是傻了..这题明 ...

  2. Qt tableWidget 空单元格 获取选中行行号

    bool focus = tableWidget->isItemSelected(tableWidget->currentItem()); // 判断是否选中一行 Int row1 = t ...

  3. UVALive 6467 Strahler Order(拓扑序列)

    In geology, a river system can be represented as a directed graph. Each river segment is an edge; wi ...

  4. WebGL学习笔记四点一

    上一章是对图形的变换,这一章的第一节主要介绍了光栅化的过程,在创建多个颜色的三角形的过程中顶点着点器的过程如下 ,1.首先通过attribute的变量从javascript中获取数据,根据drawAr ...

  5. C# CHM帮助文档

    1.生成chm文件 首先,下载EasyCHM软件,此软件可将HTML文件.TXT文件.图片和文件夹按照文件层次生成.chm文件.EasyCHM打开界面如图所示: 点击“新建”,选择需要生成.chm文件 ...

  6. Beta 冲刺1

    队名:日不落战队 安琪(队长) 过去两天完成了那些任务 修改个人信息界面. 修改手写涂鸦界面. 接下来的任务 改进手写涂鸦,加入其他功能. 还剩下的任务 社交模块功能. 遇到的困难 无. 有哪些收获和 ...

  7. Maven教程--02设置Maven本地仓库|查看Maven中央仓库

    一:设置Maven本地仓库 Maven默认仓库的路径:~\.m2\repository,~表示我的个人文档:例如:C:\Users\Edward\.m2\repository:如下图: Maven的配 ...

  8. 对于Redis的了解

    Redis :高性能的key-value数据库,支持存储的value类型包括字符串.链表.集合.有序集合.哈希类型. redis使用两种文件格式:全量数据和增量请求. 全量数据格式是将内存中的数据写入 ...

  9. 第三周作业(三)WordCount

    这个程序主要就是统计一下文件中的字符数,单词数以及行数. 我的程序很简单,代码很简短,只实现了书中的基本功能. #include <stdio.h> #include <string ...

  10. Redis有序集内部实现原理分析

    Redis技术交流群481804090 Redis:https://github.com/zwjlpeng/Redis_Deep_Read Redis中支持的数据结构比Memcached要多的多啦,如 ...