n Java world, JSON is becoming de facto standard for data exchange format over XML because of its ease of use and efficiency in terms of transferring it.
If you don’t know about JSON, it is Javascript object notation, a text based data exchange format which is collection of name-value where name is strictly of string type and value can be int, boolean, array or another json object.
GSON is open source Java library developed by Google. It is an API for converting a Java object to/from json representation.
Why should you use it ?
- Converts any Java object i.e new object or any existing/legacy object, to JSON and vice-versa.
- Finest support for generic objects
- Simple, convenient methods for conversions
- No need of any annotation for fields for conversions
- All the fields by default are included in conversions even private fields
- If don’t want to include the field in conversion, use transient modifier for that field
- It handles the null fields gracefully, by not including them in serialization output but during deserialization it is initialized back to null
How do you add it to project ?
Add it as dependency using one of following way
Using Maven
Add the following dependency to project’s pom.xml
2 |
< groupId >com.google.code.gson</ groupId >
|
3 |
< artifactId >gson</ artifactId >
|
4 |
< version >2.2.4</ version >
|
Using Gradle
Add following to project’s build.gradle
6 |
compile 'com.google.code.gson:gson:2.2.4'
|
Use as unmanaged dependency
If you are not using any build tool, you can add gson jar to directly classpath or build path.
Download the latest jar from GSON project’s downloads page. The downloaded zip file contains 3 jar files – the binary, the source code and the javadoc. Grab the binary jar file and add it to your project classpath.
How to use it ?
For conversion of an object to/from json, you need to use the Gson class and its following 2 methods.
toJson() => converts an object provided to json string, takes object to be converted as argument and returns the json representation string
fromJSon() => converts the json string to object, takes first param as json string as object and class literal of destination object and returns the destination object
You can use Gson instance/object multiple times as it does not maintain any state.
Following are few examples stating the use of GSON API.
Example 1 : For simple object
Consider the following model object for conversion purpose, but remember that you can convert any object
ModelObject.java
01 |
package in.ajduke.ap012;
|
03 |
* An model for gson demo |
07 |
public class ModelObject {
|
13 |
public ModelObject(String name, int val,
|
14 |
boolean status, double f) {
|
23 |
public String toString() {
|
24 |
return "ModelObject [name=" + name + ",
|
25 |
val= " + val + " , status="
|
26 |
+ status + ", f=" + f + "]" ;
|
Following is listing for conversion object to json representation,
Example1.java
01 |
final Gson gson = new Gson();
|
03 |
ModelObject modelObject = new ModelObject( "myname" , 12 , true , 2.3 );
|
04 |
System.out.println( "toJson ---" );
|
05 |
System.out.println( "Original Java object : " + modelObject);
|
07 |
String json = gson.toJson(modelObject); |
08 |
System.out.println( "Converted JSON string is : " + json);
|
10 |
System.out.println( "fromJson----" );
|
12 |
System.out.println( "Original JSON string is : " + json);
|
14 |
ModelObject modelObject1 = gson.fromJson(json, ModelObject. class );
|
15 |
System.out.println( "Converted Java object : " + modelObject1);
|
Note the signature of fromJson() it takes second argument as the class literal of destination object.
Output as follows,
Example-1-output
toJson ---
Original Java object : ModelObject [name=myname, val=12, status=true, f=2.3]
Converted JSON string is : {"name":"myname","val":12,"status":true,"f":2.3}
fromJson----
Original JSON string is : {"name":"myname","val":12,"status":true,"f":2.3}
Converted Java object : ModelObject [name=myname, val=12, status=true, f=2.3]
Example 2 : For generic objects
For converting back the generic object to java object from json representation, we need to use use extra object as shown in follows
Type collectionType =new TypeToken<{ generic-object-with-type-information }>(){}.getType();
You need to provide the destination class type to TypeToken type parameter information as shown above. This is to form the Type instance and this we need to pass it to fromJson() method as second argument.
Following listing shows example for conversion of generic classes or the classes from collections framework to/from json
GenericModel.java
01 |
package in.ajduke.ap012;
|
03 |
* An generified model for demo of gson conversion |
06 |
public class GenericModel<T> {
|
09 |
public GenericModel(T value) {
|
15 |
public String toString() {
|
16 |
return "Model2 [value=" + value + "]" ;
|
Example2.java
01 |
Gson gson = new Gson();
|
03 |
System.out.println( "A generic object demo" );
|
05 |
GenericModel<Integer> model = new GenericModel<>( 12 );
|
08 |
String json = gson.toJson(model); |
09 |
System.out.println( "json representation :" + json);
|
12 |
Type collectionType = new TypeToken<GenericModel<Integer>>() {
|
14 |
GenericModel<Integer> modelObj = |
15 |
gson.fromJson(json, collectionType);
|
16 |
System.out.println( "converted object representation: " + modelObj);
|
18 |
System.out.println( "\nA object from collection framework\n" );
|
20 |
List<String> listOfString = new ArrayList<>();
|
21 |
listOfString.add( "ajduke" );
|
22 |
listOfString.add( "ajduchess" );
|
25 |
String jsonStr = gson.toJson(listOfString); |
26 |
System.out.println( "json representation :" + jsonStr);
|
28 |
Type collectionType2 = new TypeToken<List<String>>() {
|
30 |
List<String> listObj = gson.fromJson(jsonStr, collectionType2); |
31 |
System.out.println( "converted object representation: " + listObj);
|
Output as follows
Example2-output
A generic object demo
json representation :{"value":12}
converted object representation: Model2 [value=12]
A object from collection framework
json representation :["ajduke","ajduchess"]
converted object representation: [ajduke, ajduchess]
Example 3 : using transient
If you don’t want to include some field in json representation, you can use transient modifier to an variable declaration, then while converting it to json representation, GSON ignores that variable. But when converting back to an object from json string it initializes itsdefault value depending on variable type.
Consider our ModelObject and lets skip the integer val from json representation so, modify the its declaration to transient as in following listing
ModelObject2.java
01 |
package in.ajduke.ap012;
|
03 |
* An model for demo of gson conversion |
07 |
public class ModelObject {
|
13 |
public ModelObject(String name, int val,
|
14 |
boolean status, double f) {
|
23 |
public String toString() {
|
24 |
return "ModelObject [name=" + name + ",
|
25 |
val= " + val + " , status="
|
26 |
+ status + ", f=" + f + "]" ;
|
Following is listing
Example3.java
01 |
Gson gson = new Gson();
|
03 |
ModelObject modelObject = new ModelObject( "namesake" , 50 , true , 4.3 );
|
04 |
System.out.print( "Original Java object : " );
|
05 |
System.out.println(modelObject); |
08 |
String json = gson.toJson(modelObject); |
09 |
System.out.print( "Converted JSON string is : " );
|
10 |
System.out.println(json); |
13 |
ModelObject modelObject3 = gson.fromJson(json, ModelObject. class );
|
14 |
System.out.print( "Converted Java object : " );
|
15 |
System.out.println(modelObject3); |
So, while converting it GSON ignores and output of above as follows
example3-output
Original Java object : ModelObject [name=namesake, val=50, status=true, f=4.3]
Converted JSON string is : {"name":"namesake","status":true,"f":4.3}
Converted Java object : ModelObject [name=namesake, val=0, status=true, f=4.3]
Thats all folks, for GSON introduction !!
Note: I had given small code snippet for all examples, to access full length listing go to this gist on github
相关推荐
谷歌Gson库是Java开发中广泛使用的JSON解析和序列化工具,版本2.8.0是其一个稳定且功能丰富的版本。JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,易于人阅读和编写,同时也易于机器解析和生成。...
标题"Google gson jar包"暗示了我们讨论的是Google Gson库的Java档案文件(JAR),它包含了所有必要的类和资源,使开发者能够在项目中直接使用Gson功能。JAR文件通常在Java开发中用于封装库,以便在应用程序中作为...
包含以下java源文件: com.google.gson.DefaultDateTypeAdapter.class com.google.gson.ExclusionStrategy.class com.google.gson.FieldAttributes.class com.google.gson.FieldNamingPolicy.class ...
谷歌的Gson库是Java和Android开发者用于在JSON对象与Java对象之间进行转换的强大工具。它的全称是Google Gson,允许我们轻松地将Java对象序列化为JSON字符串,或者从JSON字符串反序列化为Java对象。这篇内容将深入...
Google Gson 是一个强大的Java库,由Google开发,用于在Java对象和JSON数据之间进行相互转换。这个库使得Java对象能够轻松地被序列化为JSON格式的字符串,同时也能将JSON字符串解析为相应的Java对象,极大地简化了...
Google Gson库提供了一个强大的工具,使得Java对象与JSON字符串之间的转换变得简单易行。本文将详细介绍如何利用Google Gson库进行JSON字符串与对象之间的相互转换。 首先,我们需要了解Gson的核心概念。Gson库通过...
在Java开发中,Google Gson库是一个非常流行的工具,用于将Java对象转换为JSON字符串,以及将JSON字符串反序列化回Java对象。这个“Google Gson解析Json数据应用实例”旨在深入探讨Gson库的使用,帮助开发者更好地...
这时,Google的Gson库就发挥了重要作用。本文将详细介绍如何在Eclipse和Android Studio环境下使用Gson库来解析Json数据。 首先,我们来看Eclipse下的Gson使用示例。在Eclipse中,你需要先引入Gson库。这可以通过在...
Google Gson是谷歌开发的一款强大的JSON解析库,它允许开发者在Java对象和JSON数据之间进行相互转换。JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,被广泛应用于Web服务和应用程序之间的数据通信...
谷歌的Gson库是一个强大的Java库,它允许开发者将Java对象转换为JSON格式的字符串,同时也能将JSON数据解析回等效的Java对象。这个工具类对于处理JSON数据,尤其是在服务器端与客户端之间的数据交换中,显得尤为重要...
Gson是Google开发的一款强大的Java库,用于在Java对象和JSON数据之间进行映射。它的全称是Google Gson,主要用于将Java对象转换为JSON格式的字符串,也可以将JSON字符串反序列化为对应的Java对象。在Java开发中,...
谷歌的Gson库是Java开发者处理JSON数据的强大工具。标题中的"google_gson_2.3.1"指的是Google发布的Gson库的2.3.1版本,这是一个用于在Java对象和JSON数据之间进行互相转换的开源库。下面将详细阐述Gson库的功能、...
Google Gson库是Java平台上的一个强大工具,用于将Java对象转换为对应的JSON表示,反之亦然。在Android Studio中,Gson库可以帮助我们方便地解析和生成JSON数据。本篇文章将详细介绍如何在Android Studio环境下使用...
在Android开发中,数据交换和存储经常涉及到JSON格式的数据,Google Gson库是一个强大的工具,用于在Java对象和JSON数据之间进行映射。本教程将详细阐述如何在Eclipse环境中使用Gson来解析JSON数据。 首先,我们...
谷歌的Gson库是Java开发者用来在JSON数据与Java对象之间进行序列化和反序列化的强大工具。JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,因其易读、易写、易于机器解析和生成的特点,被广泛应用于...
在Java开发中,Google的Gson库是一个非常重要的工具,它允许我们将Java对象转换为JSON字符串,反之亦然。这个库对于数据交换、API交互以及序列化和反序列化非常有用。本文将深入探讨`google gson`包以及如何使用它...
谷歌的Gson库是一款强大的Java库,用于将Java对象转换为JSON(JavaScript Object Notation)格式,反之亦然。这个库使得在Java应用程序中处理JSON数据变得极其简单,尤其适用于那些需要在网络通信、存储或者显示JSON...
android google gson json解析
**谷歌Gson 2.2.4:Java与JSON之间的桥梁** 谷歌Gson库是一个强大的工具,它在Java开发中扮演着重要的角色,特别是在处理JSON数据时。JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,因其简洁、易...
**标题:** 谷歌GSON - 解析JSON(Demo) **正文:** 在Android开发中,数据交换经常涉及到JSON格式,而GSON库是Google提供的一个强大的JSON处理库,它使得Java对象与JSON数据之间的转换变得极其简单。本篇文章将...