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.
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.
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.
Gson provides three alternative ways to process JSON −
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.
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.
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.
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.
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'.
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'
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'
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 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.
OS | Archive name |
---|---|
Windows | gson-2.3.1.jar |
Linux | gson-2.3.1.jar |
Mac | gson-2.3.1.jar |
Set the GSON_HOME environment variable to point to the base directory location where Gson jar is stored on your machine.
OS | Output |
---|---|
Windows | Set the environment variable GSON_HOME to C:gson |
Linux | export GSON_HOME=/usr/local/gson |
Mac | export GSON_HOME=/Library/gson |
Set the CLASSPATH environment variable to point to the Gson jar location.
OS | Output |
---|---|
Windows | Set the environment variable CLASSPATH to %CLASSPATH%;%GSON_HOME%gson-2.3.1.jar;.; |
Linux | export CLASSPATH=$CLASSPATH:$GSON_HOME/gson-2.3.1.jar:. |
Mac | export 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.
Create a Java class file named GsonTester in C:>GSON_WORKSPACE.
File − GsonTester.java
Compile the classes using javac compiler as follows −
Now run the GsonTester to see the result −
Verify the output.
Following are the important steps to be considered here.
Create a Gson object. It is a reusable object.
Use fromJson() method to get the Object from the JSON. Pass Json string / source of Json string and object type as parameter.
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.
Following is the declaration for com.google.gson.Gson class −
Sr.No | Constructor & Description |
---|---|
1 | Gson() Constructs a Gson object with default configuration. |
Sr.No | Method & 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() |
This class inherits methods from the following class −
Create the following Java program using any editor of your choice, and save it at, say, C:/> GSON_WORKSPACE
File − GsonTester.java
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.
Create a Java class file named GsonTester in C:>GSON_WORKSPACE.
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 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.
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
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.
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.
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.
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.
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.
Create a Java class file named GsonTester in C:>GSON_WORKSPACE.
File − GsonTester.java
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.
Let's see JsonReader in action. Create a Java class file named GsonTester in C:>GSON_WORKSPACE.
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.
Let's see Array serialization/de-serialization in action. Create a Java class file named GsonTester in C:>GSON_WORKSPACE.
File − GsonTester.java
Compile the classes using javac compiler as follows −
Now run the GsonTester to see the result −
Verify the output.
Let's see Collection serialization/de-serialization in action. Create a Java class file named GsonTester in C:>GSON_WORKSPACE.
File − GsonTester.java
Compile the classes using javac compiler as follows −
Now run the GsonTester to see the result −
Verify the output.
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.
Let's see Generics serialization/de-serialization in action. Create a Java class file named GsonTester in C:>GSON_WORKSPACE.
File − GsonTester.java
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.
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
Compile the classes using javac compiler as follows −
Now run the GsonTester to see the result −
Verify the output.
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
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 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 using GsonBuilder and create a Gson instance using GsonBuilder.
Gson will now use the custom adapter to convert Json text to object and vice versa.
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
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.
Create a Java class file named GsonTester in C:>GSON_WORKSPACE.
Compile the classes using javac compiler as follows −
Now run the GsonTester to see the result −
Verify the output.
Create a Java class file named GsonTester in C:>GSON_WORKSPACE.
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.
Let's see an example of versioning support in action. Create a Java class file named GsonTester in C:>GSON_WORKSPACE.
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.
Create a Java class file named GsonTester in C:>GSON_WORKSPACE.
File − GsonTester.java
Compile the classes using javac compiler as follows −
Now run the GsonTester to see the result −
Verify the output
GsonBuilder provides control over excluding fields with particular modifier using excludeFieldsWithModifiers() method from serialization/deserialization process. See the following example.
Create a Java class file named GsonTester in C:>GSON_WORKSPACE.
File − GsonTester.java
Compile the classes using javac compiler as follows −
Now run the GsonTester to see the result −
Verify the output
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.
Create a Java class file named GsonTester in C:>GSON_WORKSPACE.
File − GsonTester.java
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.
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.
The installers are tested by EnterpriseDB on the following platforms. They will generally work on newer versions of macOS as well:
PostgreSQL Version | 64-bit macOS Platforms |
---|---|
12 | 10.12 - 10.14 |
11 | 10.12 - 10.14 |
10 | 10.10 - 10.12 |
9.6 | 10.10 - 10.12 |
9.5 | 10.8 - 10.10 |
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.
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.
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.
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.