Skip to content
John Lusher II edited this page Feb 1, 2016 · 1 revision

Introduction to JSON and Gson

JSON, which stand for JavaScript Object Notation, is a data interchange format that was originally being used for just Java script but is used in many languages now, such at MATLAB. The predominant use of JSON is in browser/server communication and can be used in place of XML (Extensible Markup Language). For information on the background of JSON please follow these links:

http://json.org/ https://en.wikipedia.org/wiki/JSON/

Gson is a Java library that converts your Java objects, including objects in which you do not have source code for, into/from their JSON format. For information on the background of Gson please follow this GitHub link:

https://github.com/google/gson/blob/master/UserGuide.md

Example of JSON vs. XML

from reference: http://www.w3schools.com/json/


The following JSON example defines an employees object, with an array of 3 employee records:

JSON Example

{"employees":[
    {"firstName":"John", "lastName":"Doe"},
    {"firstName":"Anna", "lastName":"Smith"},
    {"firstName":"Peter", "lastName":"Jones"}
]}

The following XML example also defines an employees object with 3 employee records:

XML Example

<employees>
    <employee>
        <firstName>John</firstName> <lastName>Doe</lastName>
    </employee>
    <employee>
        <firstName>Anna</firstName> <lastName>Smith</lastName>
    </employee>
    <employee>
        <firstName>Peter</firstName> <lastName>Jones</lastName>
    </employee>
</employees>

How to use JSON and Gson in our applications

Go to the following link, https://github.com/google/gson, and also download the Java library (Jar) from this link http://search.maven.org/#artifactdetails%7Ccom.google.code.gson%7Cgson%7C2.5%7Cjar. Add the library to your project, which is done in the Project Structure section in IntelliJ.

I created a test class to use for demonstration, which is shown here:

//  --------------------------------------------------------------------------------------------------------------------
//        Class:    Members
//  Description:	Members class - simple test class for JSON / Gson example
//  --------------------------------------------------------------------------------------------------------------------
public class Members
{
    public int ID;
    public String firstName;
    public String lastName;
    public String phoneNumber;

    //	----------------------------------------------------------------------------------------------------------------
    //    Function:     Members - Constructor
    //      Inputs:	    none
    //     Outputs:	    none
    //  Description:    Simple test class
    //	----------------------------------------------------------------------------------------------------------------
    public Members()
    {
                                                                        // ---------------------------------------------
        ID = -1;                                                        // Default ID is -1 (undefined)
                                                                        // ---------------------------------------------
    }
}

In your class that you are using Gson you will need to include the following imports:

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

You will then create a new instance of the GsonBuilder class to build JSON from an object, such as:

        Gson gson = new GsonBuilder().create();                         // Create Gson builder
        gson.toJson(testperson, System.out);                            // Convert object to JSON and send out

Here is some example code to try in your project:

//  --------------------------------------------------------------------------------------------------------------------
//  Imports
//  --------------------------------------------------------------------------------------------------------------------
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.*;

//  --------------------------------------------------------------------------------------------------------------------
//        Class:    Main
//  Description:	Main class for project
//  --------------------------------------------------------------------------------------------------------------------
public class Main
{
    //	----------------------------------------------------------------------------------------------------------------
    //    Function:     Class Construction
    //      Inputs:	    arguments
    //     Outputs:	    none
    //  Description:    Defines and initializes the class: main
    //	----------------------------------------------------------------------------------------------------------------
    public static void main(String[] args)
    {
                                                                        // ---------------------------------------------
        Members testperson = new Members();                             // Create example member
                                                                        // ---------------------------------------------

                                                                        // ---------------------------------------------
        testperson.lastName = "Lusher";                                 // Set some values
        testperson.firstName = "John";                                  //
        testperson.phoneNumber = "(979) 229-1950";                      //
        testperson.ID = 1;                                              //
                                                                        // ---------------------------------------------

                                                                        // ---------------------------------------------
        Gson gson = new GsonBuilder().create();                         // Create Gson builder
        gson.toJson(testperson, System.out);                            // Convert to JSON and send out the console
                                                                        //
        System.out.println();                                           // Print blank line x 2
        System.out.println();                                           //
                                                                        //
        try                                                             // Catch and file expections
        {                                                               //
            Writer writer = new FileWriter("Output.json");              // Create file writer - filename  Output.json
            Reader reader = new FileReader("Input.json");               // Create file reader - filename  Input.json
                                                                        //
            gson.toJson(testperson, writer);                            // now send out via the file writer
            Members newperson = gson.fromJson(reader, Members.class);   // now read via file reader, create new person
                                                                        //
            System.out.println("New Person via JSON file");             // Print out new person data
            System.out.println("        ID: " + newperson.ID);          //
            System.out.println("First Name: " + newperson.firstName);   //
            System.out.println(" Last Name: " + newperson.lastName);    //
            System.out.println("   Phone #: " + newperson.phoneNumber); //
                                                                        //
            writer.close();                                             // Clean up objects, close writer/reader
            reader.close();                                             //
        }                                                               //
        catch (IOException ioException)                                 // Process exception
        {                                                               //
            ioException.printStackTrace();                              // Just printout the exception trace
        }                                                               //
                                                                        // ---------------------------------------------
    }
}

Here is the data in the Output.json file.

{"ID":1,"firstName":"John","lastName":"Lusher","phoneNumber":"(979) 229-1950"}

As you can see JSON and Gson work very well and are easy to implement in your code to send (serialize) your classes without having to make the classes themselves be serializable.

Clone this wiki locally