Google Gson用法
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用法的更多相关文章
- Android网络之数据解析----使用Google Gson解析Json数据
[声明] 欢迎转载,但请保留文章原始出处→_→ 生命壹号:http://www.cnblogs.com/smyhvae/ 文章来源:http://www.cnblogs.com/smyhvae/p/4 ...
- Java创建和解析Json数据方法(五)——Google Gson包的使用
(五)Google Gson包的使用 1.简介 Gson包中,使用最多的是Gson类的toJson()和fromJson()方法: ①toJson():将java对象转化为json数据 ...
- [转]Json转换神器之Google Gson的使用
这几天,因为项目的需要,接触了Google的Gson库,发现这个东西很好用,遂记下简单的笔记,供以后参考.至于Gson是干什么的,有什么优点,请各位同学自行百度.话不多说,切入正题: 1. 下载Gso ...
- [转]使用 google gson 转换Timestamp或Date类型为JSON字符串.
创建类型适配类: import java.lang.reflect.Type; import java.sql.Timestamp; import java.text.DateFormat; impo ...
- 使用 google gson 转换Timestamp或Date类型为JSON字符串.
http://blog.csdn.net/z69183787/article/details/13016289 创建类型适配类: import java.lang.reflect.Type; impo ...
- 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 ...
- org.json.JSONObject与com.google.gson.Gson
org.json库为JSON创始人编写的解析JSON的java库,Gson为Google为我们提供的解析JSON格式数据的库. Gson里最重要的对象有2个Gson 和GsonBuilder. Gso ...
- 使用 google gson 转换Timestamp为JSON字符串
package com.test.base; import java.lang.reflect.Type; import java.sql.Timestamp; import java.text.Da ...
- Google Gson解析Json数据应用实例
转自:http://lixigao449778967.blog.163.com/blog/static/24985164201269105928783/ 1.需要的Jar包 1) Google Gso ...
随机推荐
- Linux 磁盘与文件系统(EXT2)简介
Linux 中,一切(或几乎一切)都是文件. 一.Linux 磁盘分区与文件系统 1.1 磁盘分区 磁盘的分区主要分为主分区和扩展分区 1)主分区:总共最多只能有四个主分区: 2)扩展分区:只能有一个 ...
- more和less命令详解
基础命令学习目录首页 原文链接:https://www.cnblogs.com/aijianshi/p/5750911.html 一.more命令 more功能类似 cat ,cat命令是整个文件的内 ...
- Kubernetes探索学习004--深入Kubernetes的Pod
深入研究学习Pod 首先需要认识到Pod才是Kubernetes项目中最小的编排单位原子单位,凡是涉及到调度,网络,存储层面的,基本上都是Pod级别的!官方是用这样的语言来描述的: A Pod is ...
- Scrum Meeting 6 -2014.11.12
今天apec最后一天,大部分任务都差不多了,局部测试问题不大.大家修复下小细节就可以开始整合了. Member Today’s task Next task 林豪森 协助测试及服务器部署 协助测试及服 ...
- 爱码室Crawler & classification module项目工作分配
项目情况 爬虫项目是上届学生遗留下来的项目,他们已经实现了基础的功能,而我们来负责完善,主要需要解决的问题是怎么让爬虫脱离爬和停的繁琐指令,更加的智能化.所以我们的计划是在前人的源码基础上,加以修改测 ...
- Scrum Meeting 10.23
Scrum Meeting No.3 今天所完成的任务仍然停留在学习基础知识上.说实话,由于缺少安卓开发.web开发的经验,我们只能一步步摸索着来. 成员 已完成任务 下一阶段任务 徐越 阅读网上的博 ...
- 灵悟礼品网上专卖店——画出E-R图
一.小组成员: 洪雪意(产品负责人) 陈淑筠(Master) 二.组内人员任务情况 计划完成的任务的第三个模块:分析并建立数据库 已完成的任务: 任务的第三个模块: 陈淑筠(完成任务1):画出商品资料 ...
- Java大数——快速矩阵幂
Java大数——快速矩阵幂 今天做了一道水题,尽管是水题,但是也没做出来.最后问了一下ChenJ大佬,才慢慢的改对,生无可恋了.... 题目描述: 给a,b,c三个数字,求a的b次幂对c取余. 数据范 ...
- APP案例分析之华为浏览器
第一部分 对华为浏览器的调研,评测 1.对华为浏览器的第一次上手体验 我会使用华为浏览器呢,是因为我买的手机是华为nova,该浏览器也是手机里面预装的.刚开始用的时候也没太注意,感觉跟以前用的其他浏 ...
- ANR基础
转自:http://blog.sina.com.cn/s/blog_c0de2be70102wd1k.html 1.ANR basic knowledge ANR分类: Key Dispatch Ti ...