• Gson Tutorial

In this tutorial, we'll learn about the HttpClient library introduced in Java 11 for sending HTTP requests. We'll also see how to use the Gson library from Google to parse JSON data. We'll be using a single source file for our app which can be executed in Java 11 using the java command without first compiling it (using javac)just like a script file.

  • Gson Useful Resources
  • Selected Reading

Google Gson is a simple Java-based library to serialize Java objects to JSON and vice versa. It is an open-source library developed by Google.

The following points highlight why you should be using this library −

  • Standardized − Gson is a standardized library that is managed by Google.

  • Efficient − It is a reliable, fast, and efficient extension to the Java standard library.

  • Optimized − The library is highly optimized.

  • Support Generics − It provides extensive support for generics.

  • Supports complex inner classes − It supports complex objects with deep inheritance hierarchies.

Features of Gson

Here is a list of some of the most prominent features of Gson −

  • Easy to use − Gson API provides a high-level facade to simplify commonly used use-cases.

  • No need to create mapping − Gson API provides default mapping for most of the objects to be serialized.

  • Performance − Gson is quite fast and is of low memory footprint. It is suitable for large object graphs or systems.

  • Clean JSON − Gson creates a clean and compact JSON result which is easy to read.

  • No Dependency − Gson library does not require any other library apart from JDK.

  • Open Source − Gson library is open source; it is freely available.

Three Ways of Processing JSON

Gson provides three alternative ways to process JSON −

Streaming API

It reads and writes JSON content as discrete events. JsonReader and JsonWriter read/write the data as token, referred as JsonToken.

It is the most powerful approach among the three approaches to process JSON. It has the lowest overhead and it is quite fast in read/write operations. It is analogous to Stax parser for XML.

Tree Model

It prepares an in-memory tree representation of the JSON document. It builds a tree of JsonObject nodes. It is a flexible approach and is analogous to DOM parser for XML.

Data Binding

It converts JSON to and from POJO (Plain Old Java Object) using property accessor. Gson reads/writes JSON using data type adapters. It is analogous to JAXB parser for XML.

Look for the Link Speed entry. Select Hardware, then select Card Reader. Flash

Local Environment Setup

If you still want to set up a local environment for Java programming language, then this section will guide you on how to download and set up Java on your machine. Please follow the steps given below, to set up the environment.

Java SE is freely available from the link Download Java. So you download a version based on your operating system.

Follow the instructions to download Java and run the .exe to install Java on your machine. Once you have installed Java on your machine, you would need to set the environment variables to point to their correct installation directories.

Setting up the Path in Windows 2000/XP

Assuming you have installed Java in c:Program Filesjavajdk directory −

  • Right-click on 'My Computer' and select 'Properties'.

  • Click on the 'Environment variables' button under the 'Advanced' tab.

  • Next, alter the 'Path' variable so that it also contains the path to the Java executable. For example, if the path is currently set to 'C:WINDOWSSYSTEM32', then change your path to read 'C:WINDOWSSYSTEM32;c:Program Filesjavajdkbin'.

Setting up the Path in Windows 95 / 98 / ME

Assuming you have installed Java in c:Program Filesjavajdk directory −

  • Edit the 'C:autoexec.bat' file and add the following line at the end: 'SET PATH=%PATH%;C:Program Filesjavajdkbin'

Setting up the Path for Linux, UNIX, Solaris, FreeBSD

The environment variable PATH should be set to point to where the Java binaries have been installed. Refer to your shell documentation if you have trouble doing this.

For example, if you use bash as your shell, then you would add the following line to the end of your '.bashrc: export PATH=/path/to/java:$PATH'

Popular Java Editors

To write your Java programs, you will need a text editor. There are quite a few sophisticated IDEs available in the market. But for now, you can consider one of the following −

  • Notepad − On Windows, you can use any simple text editor like Notepad (Recommended for this tutorial) or TextPad.

  • Netbeans − It is a Java IDE that is open-source and free which can be downloaded from https://netbeans.org/index.html.

  • Eclipse − It is also a Java IDE developed by the Eclipse open-source community and can be downloaded from https://www.eclipse.org/.

Download Gson Archive

Download the latest version of Gson jar file from gson-2.3.1.jar. At the time of writing this tutorial, we downloaded gson-2.3.1.jar and copied it into C:>gson folder.

OSArchive name
Windowsgson-2.3.1.jar
Linuxgson-2.3.1.jar
Macgson-2.3.1.jar

Set Gson Environment

Set the GSON_HOME environment variable to point to the base directory location where Gson jar is stored on your machine.

OSOutput
WindowsSet the environment variable GSON_HOME to C:gson
Linuxexport GSON_HOME=/usr/local/gson
Macexport GSON_HOME=/Library/gson

Set CLASSPATH variable

Set the CLASSPATH environment variable to point to the Gson jar location.

OSOutput
WindowsSet the environment variable CLASSPATH to %CLASSPATH%;%GSON_HOME%gson-2.3.1.jar;.;
Linuxexport CLASSPATH=$CLASSPATH:$GSON_HOME/gson-2.3.1.jar:.
Macexport CLASSPATH=$CLASSPATH:$GSON_HOME/gson-2.3.1.jar:.

Before going into the details of the Google Gson library, let's see an application in action. In this example, we've created a Student class. We'll create a JSON string with student details and deserialize it to student object and then serialize it to an JSON String.

Example

Create a Java class file named GsonTester in C:>GSON_WORKSPACE.

File − GsonTester.java

Verify the result

Compile the classes using javac compiler as follows −

Now run the GsonTester to see the result −

Verify the output.

Steps to Remember

Following are the important steps to be considered here.

Step 1 − Create Gson object using GsonBuilder

Create a Gson object. It is a reusable object.

Step 2 − Deserialize JSON to Object

Use fromJson() method to get the Object from the JSON. Pass Json string / source of Json string and object type as parameter.

Step 3 − Serialize Object to JSON

Use toJson() method to get the JSON string representation of an object.

Gson is the main actor class of Google Gson library. It provides functionalities to convert Java objects to matching JSON constructs and vice versa. Gson is first constructed using GsonBuilder and then, toJson(Object) or fromJson(String, Class) methods are used to read/write JSON constructs.

Class Declaration

Following is the declaration for com.google.gson.Gson class −

Constructors

Sr.NoConstructor & Description
1

Gson()

Constructs a Gson object with default configuration.

Class Methods

Sr.NoMethod & Description
1

<T> T fromJson(JsonElement json, Class<T> classOfT)

This method deserializes the Json read from the specified parse tree into an object of the specified type.

2

<T> T fromJson(JsonElement json, Type typeOfT)

This method deserializes the Json read from the specified parse tree into an object of the specified type.

3

<T> T fromJson(JsonReader reader, Type typeOfT)

Reads the next JSON value from reader and convert it to an object of type typeOfT.

4

<T> T fromJson(Reader json, Class<T> classOfT)

This method deserializes the Json read from the specified reader into an object of the specified class.

5

<T> T fromJson(Reader json, Type typeOfT)

This method deserializes the Json read from the specified reader into an object of the specified type.

6

<T> T fromJson(String json, Class<T> classOfT)

This method deserializes the specified Json into an object of the specified class.

7

<T> T fromJson(String json, Type typeOfT)

This method deserializes the specified Json into an object of the specified type.

8

<T> TypeAdapter<T> getAdapter(Class<T> type)

Returns the type adapter for type.

9

<T> TypeAdapter<T> getAdapter(TypeToken<T> type)

Returns the type adapter for type.

10

<T> TypeAdapter<T> getDelegateAdapter(TypeAdapterFactory skipPast, TypeToken<T> type)

This method is used to get an alternate type adapter for the specified type.

11

String toJson(JsonElement jsonElement)

Converts a tree of JsonElements into its equivalent JSON representation.

12

void toJson(JsonElement jsonElement, Appendable writer)

Writes out the equivalent JSON for a tree of JsonElements.

13

void toJson(JsonElement jsonElement, JsonWriter writer)

Writes the JSON for jsonElement to writer.

14

String toJson(Object src)

This method serializes the specified object into its equivalent Json representation.

15

void toJson(Object src, Appendable writer)

This method serializes the specified object into its equivalent Json representation.

16

String toJson(Object src, Type typeOfSrc)

This method serializes the specified object, including those of generic types, into its equivalent Json representation.

17

void toJson(Object src, Type typeOfSrc, Appendable writer)

This method serializes the specified object, including those of generic types, into its equivalent Json representation.

18

void toJson(Object src, Type typeOfSrc, JsonWriter writer)

Writes the JSON representation of src of type typeOfSrc to writer.

19

JsonElement toJsonTree(Object src)

This method serializes the specified object into its equivalent representation as a tree of JsonElements.

20

JsonElement toJsonTree(Object src, Type typeOfSrc)

This method serializes the specified object, including those of generic types, into its equivalent representation as a tree of JsonElements.

21

String toString()

Methods inherited

This class inherits methods from the following class −

  • java.lang.Object

Example

Create the following Java program using any editor of your choice, and save it at, say, C:/> GSON_WORKSPACE

File − GsonTester.java

Verify the result

Compile the classes using javac compiler as follows −

Now run the GsonTester to see the result −

Verify the output

Let's serialize a Java object to a Json file and then read that Json file to get the object back. In this example, we've created a Student class. We'll create a student.json file which will have a json representation of Student object.

Example

Create a Java class file named GsonTester in C:>GSON_WORKSPACE.

File - GsonTester.java

Verify the result

Compile the classes using javac compiler as follows −

Now run the GsonTester to see the result −

Verify the Output

Data Binding API is used to convert JSON to and from POJO (Plain Old Java Object) using property accessor or using annotations. It is of two types.

  • Primitives Data Binding − Converts JSON to and from Java Maps, Lists, Strings, Numbers, Booleans, and NULL objects.

  • Objects Data Binding − Converts JSON to and from any JAVA type.

Gson reads/writes JSON for both types of data bindings. Data Binding is analogous to JAXB parser for XML.

Primitives Data Binding

Primitives data binding refers to mapping of JSON to JAVA Core data types and inbuilt collections. Gson provides various inbuilt adapters which can be used to serialize/deserialize primitive data types.

Example

Let's see primitive data binding in action. Here we'll map JAVA basic types directly to JSON and vice versa.

Create a Java class file named GsonTester in C:>Gson_WORKSPACE.

File − GsonTester.java

Verify the result

Compile the classes using javac compiler as follows −

Now run the GsonTester to see the result −

Verify the output.

Object data binding refers to mapping of JSON to any JAVA Object.

Example

Let's see object data binding in action. Here we'll map JAVA Object directly to JSON and vice versa.

Create a Java class file named GsonTester in C:>GSON_WORKSPACE.

File - GsonTester.java

Verify the result

Compile the classes using javac compiler as follows −

Now run the GsonTester to see the result −

Verify the output.

Tree Model prepares an in-memory tree representation of the JSON document. It builds a tree of JsonObject nodes. It is a flexible approach and is analogous to DOM parser for XML.

Create Tree from JSON

JsonParser provides a pointer to the root node of the tree after reading the JSON. Root Node can be used to traverse the complete tree. Consider the following code snippet to get the root node of a provided JSON String.

Traversing Tree Model

Get each node using relative path to the root node while traversing the tree and process the data. The following code snippet shows how you can traverse a tree.

Example

Create a Java class file named GsonTester in C:>GSON_WORKSPACE.

File − GsonTester.java

Verify the result

Compile the classes using javac compiler as follows −

Now run the GsonTester to see the result −

Verify the output.

Streaming API is used to read JSON token by token. It reads and writes JSON content as discrete events. JsonReader and JsonWriter read/write the data as token, referred as JsonToken.

It is the most powerful approach among the three approaches to process JSON. It has the lowest overhead and it is quite fast in read/write operations. It is analogous to Stax parser for XML.

In this chapter, we will showcase the usage of GSON streaming APIs to read JSON data. Streaming API works with the concept of token and every details of Json is to be handled carefully.

Example

Let's see JsonReader in action. Create a Java class file named GsonTester in C:>GSON_WORKSPACE.

File - GsonTester.java

Verify the result

Compile the classes using javac compiler as follows −

Now run the GsonTester to see the result −

Verify the output.

In this chapter, we will discuss the serialization/deserialization of arrays, collections, and generics.

Array Example

Example

Let's see Array serialization/de-serialization in action. Create a Java class file named GsonTester in C:>GSON_WORKSPACE.

File − GsonTester.java

Verify the result

Compile the classes using javac compiler as follows −

Now run the GsonTester to see the result −

Verify the output.

Collections Example

Example

Let's see Collection serialization/de-serialization in action. Create a Java class file named GsonTester in C:>GSON_WORKSPACE.

File − GsonTester.java

Verify the result

Compile the classes using javac compiler as follows −

Now run the GsonTester to see the result −

Verify the output.

Generics Example

Gson uses Java reflection API to get the type of the object to which a Json text is to be mapped. But with generics, this information is lost during serialization. To counter this problem, Gson provides a class com.google.gson.reflect.TypeToken to store the type of the generic object.

Example

Let's see Generics serialization/de-serialization in action. Create a Java class file named GsonTester in C:>GSON_WORKSPACE.

File − GsonTester.java

Verify the result

Compile the classes using javac compiler as follows −

Now run the GsonTester to see the result −

Verify the output.

In this chapter, we will explain serialization/deserialization of classes having inner classes.

Nested Inner Class example

Example

Let's see an example of serialization/de-serialization of class with an inner class in action. Create a Java class file named GsonTester in C:>GSON_WORKSPACE.

File − GsonTester.java

Verify the result

Compile the classes using javac compiler as follows −

Now run the GsonTester to see the result −

Verify the output.

Nested Static Inner Class Example

Example

Let's see an example of serialization/de-serialization of class with a static inner class in action. Create a Java class file named GsonTester in C:>GSON_WORKSPACE.

File − GsonTester.java

Verify the result

Compile the classes using javac compiler as follows −

Now run the GsonTester to see the result −

Verify the output.

Gson performs the serialization/deserialization of objects using its inbuilt adapters. It also supports custom adapters. Let’s discuss how you can create a custom adapter and how you can use it.

Create a Custom Adapter

Create a custom adapter by extending the TypeAdapter class and passing it the type of object targeted. Override the read and write methods to do perform custom deserialization and serialization respectively.

Register the Custom Adapter

Register the custom adapter using GsonBuilder and create a Gson instance using GsonBuilder.

Use the Adapter

Gson will now use the custom adapter to convert Json text to object and vice versa.

Example

Let's see an example of custom type adapter in action. Create a Java class file named GsonTester in C:>GSON_WORKSPACE.

File − GsonTester.java

Verify the result

Compile the classes using javac compiler as follows −

Now run the GsonTester to see the result −

Verify the output.

Gson by default generates optimized Json content ignoring the NULL values. But GsonBuilder provides flags to show NULL values in the Json output using the GsonBuilder.serializeNulls() method.

Example without serializeNulls Call

Create a Java class file named GsonTester in C:>GSON_WORKSPACE.

How To Install Gson For MacGson format

File - GsonTester.java

Verify the result

Compile the classes using javac compiler as follows −

Now run the GsonTester to see the result −

Verify the output.

Example with serializeNulls call

Create a Java class file named GsonTester in C:>GSON_WORKSPACE.

File - GsonTester.java

Verify the result

Compile the classes using javac compiler as follows −

Now run the GsonTester to see the result −

Verify the output.

Gson provides @Since annotation to control the Json serialization/deserialization of a class based on its various versions. Consider the following class with versioning support. In this class, we've initially defined two variables rollNo and name and later on, we added verified as a new variable. Using @Since, we've defined rollNo and name as of version 1.0 and verified to be of version 1.1.

GsonBuilder provides the setVersion() method to serialize such versioned class.

Example

Let's see an example of versioning support in action. Create a Java class file named GsonTester in C:>GSON_WORKSPACE.

File - GsonTester.java

Verify the result

Compile the classes using javac compiler as follows −

Now run the GsonTester to see the result −

Verify the output.

By default, GSON excludes transient and static fields from the serialization/deserialization process. Let’s take a look at the following example.

Example

Create a Java class file named GsonTester in C:>GSON_WORKSPACE.

File − GsonTester.java

Verify the result

Compile the classes using javac compiler as follows −

Now run the GsonTester to see the result −

Verify the output

Using excludeFieldsWithModifiers

GsonBuilder provides control over excluding fields with particular modifier using excludeFieldsWithModifiers() method from serialization/deserialization process. See the following example.

Example

Create a Java class file named GsonTester in C:>GSON_WORKSPACE.

File − GsonTester.java

Verify the result

Compile the classes using javac compiler as follows −

Now run the GsonTester to see the result −

Verify the output

Using @Expose Annotation

Gson provides @Expose annotation to control the Json serialization/deserialization of a class based on its scope. Consider the following class with a variable having @Expose support. In this class, name and rollno variables are to be exposed for serialization. Then we've used the GsonBuilder.excludeFieldsWithoutExposeAnnotation() method to indicate that only exposed variables are to be serialized/deserialized. See the following example.

Example

Create a Java class file named GsonTester in C:>GSON_WORKSPACE.

File − GsonTester.java

Verify the result

Compile the classes using javac compiler as follows −

Now run the GsonTester to see the result −

Verify the output

PostgreSQL is the default database on macOS Server as of OS X Server version 10.7.macOS without the macOS Server add-on installed includes only the PostgreSQLlibpq shared library.

macOS Server 10.12 ships with PostgreSQL 9.4. Minor updates are providedby Apple, but not necessarily right after a new PostgreSQL minor release.

There are several other installers available for PostgreSQL on macOS,which is the recommended way to install.

Interactive installer by EnterpriseDB

Download the installercertified by EnterpriseDB for all supported PostgreSQL versions.

This installer includes the PostgreSQL server, pgAdmin; a graphical tool for managing and developingyour databases, and StackBuilder; a package manager that can be used to download and installadditional PostgreSQL tools and drivers. Stackbuilder includes management,integration, migration, replication, geospatial, connectors and other tools.

This installer can run in graphical, command line, or silent install modes.

The installer is designed to be a straightforward, fast way to get up and running withPostgreSQL on macOS.

Advanced users can also download azip archiveof the binaries, without the installer.This download is intended for users who wish to include PostgreSQL as part of another application installer.

Platform support

The installers are tested by EnterpriseDB on the following platforms. They will generally work on newer versions of macOS as well:

PostgreSQL Version64-bit macOS Platforms
1210.12 - 10.14
1110.12 - 10.14
1010.10 - 10.12
9.610.10 - 10.12
9.510.8 - 10.10

Postgres.app

Postgres.app is a simple, native macOS app that runs in the menubar without the need of an installer. Open the app, and you have a PostgreSQL serverready and awaiting new connections. Close the app, and the server shuts down.

Fink

PostgreSQL packages are available for macOS from theFink Project.Please see the Fink documentation for information on how to install packages.

A list ofPostgreSQL packagescan be found using the package search tool on the Fink website.

MacPorts

PostgreSQL packages are also available for macOS from theMacPorts Project. Please see theMacPorts documentation for information on how to install ports.

A list ofPostgreSQL packagescan be found using the portfiles search tool on the MacPorts website.

Homebrew

PostgreSQL can also be installed on macOSusing Homebrew. Please see the Homebrewdocumentation for information on how to install packages.

A listof PostgreSQLpackages can be found using the Braumeister search tool.

Latest Posts
  • Scribblenauts Unlimited Mac Italy
  • How To Download App For Windows On Mac
  • Cara Game Diner Dash 2
  • League Client Doesnt Close For Mac
  • Download Windows Free Trial For Mac
  • Nosgoth For Mac
  • Qnap Mycloud App For Mac
  • Auto Tune 5 Rtas Free Version Download For Mac
  • Nutrition Label Software For Mac
  • Download Wechat For Mac