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. WinDbg使用学习

    拿到软件崩溃之后产生的crash文件,后缀名为dump 使用winDbg的File-----> Open Crash Dump 打开Crash文件 File---------> Symbo ...

  2. IDEA 2018 最新激活码 License server

    IDEA 2018 最新激活码 License server 总会有一个属于适合你的!嘻嘻 http://hb5.s.osidea.cc:1017 http://idea.youbbs.org htt ...

  3. jenkins部署时遇到“似乎无法联网”,导致无法安装默认插件的解决方案

    jenkins安装更新时,默认会检查网络连接,而默认的checkulr 是http://www.google.com/ ,国内是无法访问的,所以修改成任意可以访问的地址即可,比如http://www. ...

  4. 配置idea

    http://www.cnblogs.com/yangyquin/p/5285272.html

  5. [buaa-SE-2017]个人作业-week3

    个人作业-week3:案例分析 分析产品:Bing词典 Part1:调研&评测 1.软件评测和Bug汇报 这次我选择Bing词典的原因是在于,首先我使用过的词典软件较多,平台涵盖PC端.网站. ...

  6. iOS开发学习-如何优化tableview的使用

    1.复用单元格 2.单元格中的视图尽量都使用不透明的,单元格中尽量少使用动画 3.图片加载使用异步加载 4.滑动时不加载图片,停止滑动时开始加载 5.单元格中的内容可以在自定义cell类中的drawR ...

  7. spring冲刺第三天

    昨天完成了环境配置和初步的地图设想. 今天从网上找了有关这方面的例子,运行试验了一番.编写的地图画面在程序上运行了一下,有些错误,还需要很多方面的改进. 这些例子有很多地方都不太懂,但还是看完了.我认 ...

  8. 2018软工实践第八次作业-团队项目UML设计

    团队信息 队员姓名与学号 学号 姓名 博客链接 124 王彬(组长) 点击这里 206 赵畅 点击这里 215 胡展瑞 点击这里 320 李恒达 点击这里 131 佘岳昕 点击这里 431 王源 点击 ...

  9. lintcode-514-栅栏染色

    514-栅栏染色 我们有一个栅栏,它有n个柱子,现在要给柱子染色,有k种颜色可以染. 必须保证不存在超过2个相邻的柱子颜色相同,求有多少种染色方案. 注意事项 n和k都是非负整数 样例 n = 3, ...

  10. CSS+JS笔记

    CSS篇: 1.a标签去掉下划线 a { text-decoration:none; }