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 ...
随机推荐
- 【Unity Shader】渲染管线
流程概述 应用程序阶段 应用程序阶段,使用高级编程语言(C.C++.JAVA 等)进行开发,主要和CPU.内存打交道,诸如碰撞检测.场景图建立.空间八叉树更新.视锥裁剪等经典算法都在此阶段执行.在该阶 ...
- Spark计算模型RDD
RDD弹性分布式数据集 RDD概述 RDD(Resilient Distributed Dataset)叫做弹性分布式数据集,是Spark中最基本的数据抽象,它代表一个不可变.可分区.里面的元素可并行 ...
- [Paper Reading] Image Captioning using Deep Neural Architectures (arXiv: 1801.05568v1)
Main Contributions: A brief introduction about two different methods (retrieval based method and gen ...
- NO.5:自学python之路------标准库,正则表达式
引言 时间过的好快呀,终于6级也考完了,学习Python的进度也得赶赶了.好的开始这一周的内容. 正文 模块 模块的本质就是‘.py’结尾的文件,它可以用来从逻辑上组织Python代码,它可以是变量. ...
- ifconfig命令详情
基础命令学习目录首页 原文链接:https://blog.csdn.net/weixin_37886382/article/details/79716879 许多windows非常熟悉ipconfig ...
- final发布视频展示博客
Part One [探路者]选题展示视频链接: http://v.youku.com/v_show/id_XMzIxMDM2MTQ1Ng==.html?spm=a2h3j.8428770.341605 ...
- Bing词典vs有道词典比对测试报告
功能篇 核心功能测评:http://www.cnblogs.com/C705/p/4075554.html 细节与用户体验:http://www.cnblogs.com/C705/p/4077112. ...
- oo第八次作业--5,6,7次作业总结
一.多线程的设计 这三次作业的主要内容就是使用多线程并且解决多线程中出现的问题.而对于多线程我也有了自己的理解.首先明确的一点是单个CPU在同一时间只能处理一件事.那么,不管是多进程还是多线程,我们的 ...
- Class 1
“在最艰苦的时候,就是你离成功最近的时候”,让暴风雨来得更猛烈些吧. 健身教练/学员,买的那本Java Web还是那么新,显然假期偷懒了,只能一点一点的补回来了.一个假期没有打开过自己的脑洞,真心醉了 ...
- 进阶系列(12)—— C#异步编程
一.What's 异步? 启动程序时,系统会在内存中创建一个新的进程.进程是构成运行程序资源的集合. 在进程内部,有称为线程的内核对象,它代表的是真正的执行程序.系统会在 Main 方法的第一行语句就 ...