当前位置:首页 > 开发 > 互联网 > 正文

Google GSON

发表于: 2013-08-14   作者:cywhoyi   来源:转载   浏览次数:
摘要: 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 Jav

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

1 <dependency>
2     <groupId>com.google.code.gson</groupId>
3     <artifactId>gson</artifactId>
4     <version>2.2.4</version>
5 </dependency>

Using Gradle

Add following to project’s build.gradle

1 repositories {
2     mavenCentral()
3 }
4   
5 dependencies {
6     compile 'com.google.code.gson:gson:2.2.4'
7 }

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;
02 /**
03 * An model for gson demo 
04
05 * @author ajduke
06 */
07 public class ModelObject {
08   String name;
09   int val;
10   boolean status;
11   double f;
12    
13   public ModelObject(String name, int val, 
14   boolean status, double f) {
15     super();
16     this.name = name;
17     this.val = val;
18     this.status = status;
19     this.f = f;
20   }
21    
22   @Override
23   public String toString() {
24     return "ModelObject [name=" + name + ",
25     val=" + val + ", status="
26     + status + ", f=" + f + "]";
27   }
28  
29 }

Following is listing for conversion object to json representation,

Example1.java

01 final Gson gson = new Gson();
02 // original object instantiation
03 ModelObject modelObject = new ModelObject("myname"12true2.3);
04 System.out.println("toJson ---");
05 System.out.println("Original Java object : " + modelObject);
06 // converting an object to json object
07 String json = gson.toJson(modelObject);
08 System.out.println("Converted JSON string is : " + json);
09  
10 System.out.println("fromJson----");
11 // getting object from json representation
12 System.out.println("Original JSON string is : " + json);
13 // converting json to object
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;
02 /**
03 * An generified model for demo of gson conversion
04 * @author ajduke
05 */
06 public class GenericModel<T> {
07   T value;
08    
09   public GenericModel(T value) {
10     super();
11     this.value = value;
12   }
13    
14   @Override
15   public String toString() {
16     return "Model2 [value=" + value + "]";
17   }
18 }

Example2.java

01 Gson gson = new Gson();
02  
03 System.out.println("A generic object demo");
04 // a generified object
05 GenericModel<Integer> model = new GenericModel<>(12);
06  
07 // converting to json representation
08 String json = gson.toJson(model);
09 System.out.println("json representation :" + json);
10  
11 // converting back to object
12 Type collectionType = new TypeToken<GenericModel<Integer>>() {
13 }.getType();
14 GenericModel<Integer> modelObj =
15                   gson.fromJson(json, collectionType);
16 System.out.println("converted object representation: " + modelObj);
17  
18 System.out.println("\nA object from collection framework\n");
19 // for collection framework objects
20 List<String> listOfString = new ArrayList<>();
21 listOfString.add("ajduke");
22 listOfString.add("ajduchess");
23  
24 // conversion to json
25 String jsonStr = gson.toJson(listOfString);
26 System.out.println("json representation :" + jsonStr);
27  
28 Type collectionType2 = new TypeToken<List<String>>() {
29 }.getType();
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;
02 /**
03 * An model for demo of gson conversion
04 *
05 * @author ajduke
06 */
07 public class ModelObject {
08   String name;
09   transient int val;
10   boolean status;
11   double f;
12    
13   public ModelObject(String name, int val,
14    boolean status, double f) {
15     super();
16     this.name = name;
17     this.val = val;
18     this.status = status;
19     this.f = f;
20   }
21    
22   @Override
23   public String toString() {
24     return "ModelObject [name=" + name + ",
25     val=" + val + ", status="
26     + status + ", f=" + f + "]";
27   }
28 }

Following is listing

Example3.java

01 Gson gson = new Gson();
02 // original object
03 ModelObject modelObject = new ModelObject("namesake"50true4.3);
04 System.out.print("Original Java object : ");
05 System.out.println(modelObject);
06  
07 // converting to an json representation
08 String json = gson.toJson(modelObject);
09 System.out.print("Converted JSON string is : ");
10 System.out.println(json);
11  
12 // getting back the object from json representation
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

Google GSON

  • 0

    开心

    开心

  • 0

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

编辑推荐
SSH返回JSON格式的数据时,需要用到gson,将gson-1.6.jar添加进Build path以后运行,出错: 后来把g
【声明】 欢迎转载,但请保留文章原始出处→_→ 生命壹号:http://www.cnblogs.com/smyhvae/ 文章来
参考资料 1 java中几个json工具分析测试【原】 http://blog.csdn.net/weinianjie1/article/details/6
参考资料 1 java中几个json工具分析测试【原】 http://blog.csdn.net/weinianjie1/article/details/6
参考资料 1 java中几个json工具分析测试【原】 http://blog.csdn.net/weinianjie1/article/details/6
参考资料 1 java中几个json工具分析测试【原】 http://blog.csdn.net/weinianjie1/article/details/6
参考资料 1 java中几个json工具分析测试【原】 http://blog.csdn.net/weinianjie1/article/details/6
今天在网上瞎逛的时候发现了一个东西,发出来共享一下,就是GSON了 GSON 是什么,维基百科上的解析
参考资料 1 java中几个json工具分析测试【原】 http://blog.csdn.net/weinianjie1/article/details/6
参考资料 1 java中几个json工具分析测试【原】 http://blog.csdn.net/weinianjie1/article/details/6
版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号