Sunday, November 27, 2016

Simple GSON example

Intro

GSON is an open source Java API for serializing and deserializing JSON objects from and to Java objects, developed by Google. A purpose of this article is to provide a simple example how to use this library.

Download

GSON API could be found at maven repository. You can add the following section in your pom.xml in order to download gson.jar

 <dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.7</version>
 </dependency>

Simple Example

For this example, we need a remote storage for our JSON objects. There is a free online tool for faking JSON responses http://www.json-gen.com/

We created simple Employee  JSON object with the following structure.

{
  "id": 149859,
  "first_name": "Mike",
  "last_name": "Gonzalez",
  "date": "11/23/2016, 9:11:04 PM",
  "photo": "http://srcimg.com/100/150",
  "married": true
}







This JSON structure can be accessed via next link
 http://json-gen.com/rest/service/get/vpMW0my7SXDmOmTNu795zDeJRn

We also need a class that will represent our Employee JSON object:

As we can see, naming conventions for JSON object and Java object are not the same, so we cannot use default GSON deserializer. For that purpose, we need to create a new class that will implement our logic for deserializing.


And finally, code for main class:

1 comment:

  1. Thank you, i have a complex one can you do an other example?

    ReplyDelete