GSON is Google's library library to easily serialize and
deseralize JSON data.
Serialization is the process of changing a Java object to
JSON. While deseralization is the process of turning JSON into a Java object.
Serialization and deseralization are usually done when we
are working with a webservice.
On this occasion, we will learn to use the GSON library for
serializing and deserising JSON data directly from the code and deserising from
the webservice.
Let's get started…
Creating Projects with Maven
In this tutorial, we will use Maven to create projects and
install the GSON library.
Please type the following command to create a project with
Maven.
mvn archetype:generate \
-DgroupId=com.petanikode.app
\
-DartifactId=petanikode-app
\
-DarchetypeArtifactId=maven-archetype-quickstart
\
-DinteractiveMode=false
After that, please open this project with a text editor or
IDE.
Add the GSON Library to Project
Next we will add Si GSON by adding this depdency code:
<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
<groupId>
com.google.code.gson
</groupId>
<artifactId>
gson
</artifactId>
<version>
2.8.2
</version>
</dependency>
In file pom.xml
After that, type the following command to install it:
mvn
install
Wait until the process is complete ...
Make a Model Class
Before we can use GSON, we must create a model class that
will be the object template.
For example, we will use the User class. Please create a
User class like this:
publicclass
User
{
public
String name
,
public
int
umur
;
public
User(
String name
,String email
,int
umur
){
this.
name
=name
;
this.
this.
umur
=umur
;
}
}
Creating Main Class
To experiment, we will create a Main.java class with the
following contents:
importcom
.gson
.Gson
;
importcom
.gson
.GsonBuilder
;
publicclass
Main
{
public
static
void
main(
String
[]args
){
User mUser
=new
User("Petani Kode",
"info@petanikode.com",
22);
// ubah objek menjadi string JSON
Gson gson
=new
Gson();
String jsonUser
=gson
.toJson(mUser
);
System
.out
.println(jsonUser
);
// ubah string JSON menjadi Objek
Gson gsonBuilder
=new
GsonBuilder().create();
User myUser
=gsonBuilder
.fromJson(jsonUser
,User
.class);
System
.out
.println(myUser
.name
);
}
}
Try execution ...
... then the result:
Explanation:
Before you can use classes from the GSON library, you must
import them first.
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
After that, we try to create an object called mUser.User mUser = new User("Petani Kode", "info@petanikode.com", 22);
Next we create a Gson object and change the mUser object to JSON.
Gson gson = new Gson();
String jsonUser = gson.toJson(mUser);
System.out.println(jsonUser);
We use the toJson () method with object parameters of the class that we will convert into JSON (serialization) form.
As for the process of converting JSON into an Object, it works like this:
Gson gsonBuilder = new GsonBuilder().create();
User myUser = gsonBuilder.fromJson(jsonUser, User.class);
System.out.println(myUser.name);
First we create the GSON object from GsonBuilder (). Create (). After that, create a myUser Obejek with the method fromJson ().
The method fromJson () has two parameters:
gsonBuilder.fromJson(<string JSON>, User.class);
JSON Desrialization from Webservice
To convert JSON to a Java object from JSON data in a web service, we need an additional library. Namely: library to make HTTP Requests to the webservice.
There are lots of libraries for making HTTP Requests in Java. We will try to use the Apache HttpClient library.
Please add to the dependencies
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.4</version>
</dependency>
Do the installation again:
mvn install
After that, we will create a code to make an HTTP Request to the webservice to retrieve JSON data. Later the result of this HTTP Request will be a JSON string.
We will retrieve JSON data from: https://api.github.com/users/petanikode
The next step is to create a class for the JSON data. Please create a new class named GithubUser like this:
public class GithubUser {
String name;
String email;
String blog;
String location;
String html_url;
}
The property name used, make sure the same as the property name in the JSON. Because if not, the property will be null.
For data types, we just give them all the strings. Because the property that we want to take is all string types.
After that, modify the Main.java class like this:
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
/**
*
* @author petanikode
*/
public class Hello {
public static void main(String[] args) {
User mUser = new User("Petani Kode", "info@petanikode.com", 22);
// ubah objek menjadi string JSON
Gson gson = new Gson();
String jsonUser = gson.toJson(mUser);
System.out.println(jsonUser);
// ubah string JSON menjadi Objek
Gson gsonBuilder = new GsonBuilder().create();
User myUser = gsonBuilder.fromJson(jsonUser, User.class);
System.out.println(myUser.name);
// deserialisasi data JSON dari Webservice
try {
String jsonWeb = getJson("https://api.github.com/users/petanikode");
GithubUser gitUser = gson.fromJson(jsonWeb, GithubUser.class);
System.out.println("Hasil deserialisasi dari Webservice: ");
System.out.println(gitUser.name);
System.out.println(gitUser.email);
System.out.println(gitUser.blog);
System.out.println(gitUser.location);
System.out.println(gitUser.html_url);
} catch (Exception e) {
System.out.println("Terjadi masalah: " + e.getMessage());
}
}
public static String getJson(String url) throws Exception {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
// add request header
request.addHeader("User-Agent", "Mozilla/5.0");
HttpResponse response = client.execute(request);
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : "
+ response.getStatusLine().getStatusCode());
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
return result.toString();
}
}
In the above code, we add the getJson () method to make an HTTP Request to a webservice with the Apache HTTP Client library. The return from this method is JSON String.
Then serialized by GSON, the results will be like this: