How to Convert Java Object to/from JSON using GSON

Gson is Java JSON library that is used to convert Java object to/from JSON

GSON is developed by google.

GSON Maven dependency is as below

You can also download Gson Jar from here

Gson jar contains API to work with JSON

GOal of GSON is provide simple methods to convert and receive JSON, Provides extensive support for Generics, support complex objects

GSON provides simple functions to convert in to JSON it has toJSON() and from JSON to Java Object it has fromJSON()

Creating JSON Object

1. Gson gson=new Gson();
2. GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson1 = gsonBuilder.create();

Here Gson() is no argument constructor that will create Gson object.

Using GsonBuilder by calling create() we get Gson object

Converting Java to JSON value

Result:

Some times JSON is difficult to read to make JSON readable .setPrettyPrinting() can be used as below

GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson1= gsonBuilder.setPrettyPrinting().create();

Replace line 40 of program with second line of above code.

Then output is as below.

Serializing a custom object

Here a student class is defined it contains Address class. Create object of student and serializing it as below

Student.java

Address.java

Result

Reading Json Data from file

Parsing JSON to Java is prerformed as here.

We have saved JSON of a student (same as above structure few parameter changed) in student.json file then we are reading its content from student.json.

student = gson.fromJson(new FileReader(“d://student.json”), Student.class);

To read file from student.json File reader is used. after reading file it is converted to Student type.

Result

Reading JSON data from URL

  1. Open Connection with url
  2. Read Data using InputStreamReader
  3. Pass InputStreamReader to fromJson()

Working code is as below

@Expose annotation to serialize and de serialize fields

Annotation Export is used to serialize and deserialize fields it is defined in import com.google.gson.annotations.Expose

@Expose(serialize = true, deserialize = true) is used serialize true represents it has to be serialize same for deserialize. false value is used to not include the field in process of serialize or deserialize.

Above code Student.java and Address.java is modified as below

in main method to create object we have to use GsonBuilder as below call a method excludeFieldWithoutExposeAnnotation()

ExclusionStrategy Interface

This interface is also used to exclude any field in serializing and deserialization.

To implement ExcludeStrategy a class has to implement this.

Below is an example to remove fname field from serialization

To create Gson object use GsonBuilder as below

Exception handling in Java

Exception Handling in java

To learn about exception handling first you must know what is an exception

An exception is run time error that can occur due to wrong user input or due to logical error in programming.

Consider a simple example.

Take two integer number from command prompt and divide the number.

The code is

We complice above program

c:\> javac   division.java

while running this program we will pass

two values to program as below

  > java division 10 2

Above two values 10 and 2 known as command  line argument these values are accessed in string [] s.

There s is string array  first value 10 is stored in s[0] and second value is stored in s[1]

S is string array so we converted these string values to integer by calling Integer.parseInt(value)

Here Integer is a class and parseInt is static method used to convert string value to int value.

The converted value is stroed in a and in b

The result of division operation is

                                C= a/b;   //c = 10/2 =5 

It will store value 5 in c.

  Next statement print division is 5

This is our desired result.

What happen if user enters value 10 and 0.

What happen if user enters value 10 and 0.

  Then the statement

                                C= a/b; // c= 10/0 –

   This statement throw arithmetic exception.

    The output is a below.

Exception in thread “main” java.lang.ArithmeticException: / by zero
at division.main(division.java:5)

The above exception is due to Wrong user input.

To handle above situation we can use user input validation or exception handling.

Lets see user input validation here before division operation check whether the value of b is zero or not.

If it is zero information to user and stop the program else perform the division as below.

>javac 10 0

divisor should not be zero

This program validate the denominator is zero then print message to user else perform division operation.

Here validation is used to avoid the exception. This is good practice to validate user input to avoid exceptions.

Here we want to learn exception handling so lets see the above program with java exception handling

lets run again above code

>java Division 10 2

Division is 3

>java Division 10 0

Arithmetic Exception

In above program to handle exception try and catch blocked is used.

Inside try block the code is written which can throw exception.

The statements which can throw expection is written inside try block.

To catch the exception a catch block is used with exception type . inside the catch block appropriate exception handling is done.

Catch block executes when exception is thrown from code inside try block.

In above program int c= a/b;

exception is thrown when the value of b is zero so it should be inside try block.

The statement System.out.println(“division is “ + c); is not throwing an exception it is also inside the try block.

If division statement throw an exception. The control is passed to catch block and necessary action is performed inside catch block.

The catch block is only executed if statements inside try block throws an exception.

Lets again execute above program with value 10 and String value lets a 

>javac Division 10 a

Exception in thread "main" java.lang.NumberFormatException: For input string: "a" at java.lang.NumberFormatException.forInputString(Unknown Source) at java.lang.Integer.parseInt(Unknown Source) at java.lang.Integer.parseInt(Unknown Source) at division.main(division.java:4)

Here second value is string so throwing above exception

Integer.parseInt (s[1]) throw an exception  because it is unable to convert string to int.

In our program we handled only arithmetic exception

To handle this exception lets modify our code

again compiling and running this code

>javac Division 10 a

Please enter valid number

System.exit(1) is used to exit from program.

Here denominator is not a number so no need to continue the program.

here we used two try block and its corrosponding catch blocks.

If you want we can use one try block and multiple catch block.

Lets again change this code to handle multiple catch in single try block.

Here all type of exceptions are checked in try block when an exception is thrown based on exception a catch block is executed.

Exception is parent class for all exceptions.

Any exception thrown can handle by catching exception.

Standing multiple exceptions in program, then general exception should be last catch statement otherwise specific exception catch statement will not reached.

Concatenate & Buffer File in Java

Concatenate: It is possible to concatenate two or more files and save in a different file.

In java, by using SequenceInputStream class we can concatenate two or more files.

Buffer Files: In java, we can create a buffer to store temporary data that is read from & written to a stream and this process known as i/o buffer operation.

Buffer is  sit between programmer and source/destination file.

Buffer can be created by using following classes:

  • BufferedInputClass
  • BufferedOutputClass

Example: write a program to concatenate two file A & B and concatenated data print on output screen.

Suppose we have a File “A.txt”

Hello students I am aditya.  

 and                         File “B.txt”

Hello  

Output: Hello students I am aditya.                                                                                           Hello

Example: Write a program to copy the content of one file to another file using buffer/BufferReader.                                                                

Suppose we have a File “A .txt”                               

Hello students I am aditya.  

Output:                                              File “B”

Hello students I am aditya.  

Note: If there is no file “B” it will be create automatically.

Example: Write a program to concatenate two file A & B and save the concatenated data on a file C.

Suppose we have a File “A.txt” and File “B.txt”

Hello students I am aditya.  
Hello  

Output:               File “C”

Hello students I am aditya. Hello  

Note: Ifthere is no file “C” it will be create automatically.

File I/O with Primitive Data Type In Java

In java, basic input-output stream provides a method for reading & writing bytes or character in a file. If we want to read-write primitive data typa(such as int , float etc.) than we can use filter classes to filter data in the original stream.

DataInputStream & DataOutputStream are two filter classes used for creating “data streams” for handling primitive data type.

Example: Write a program to write & read a primitive data on a same file.

Character Stream I/O in Java

In a java programming, like a Byte stream Character stream is also used for input-output for 16 bit. But Byte streams are used to perform input and output of 8-bit.

Most common Character streams classes are, FileReader and FileWriter.

 FileReader- FileReader uses for reads two bytes at a time.

 FileWriter– FileWriter uses for writes two bytes at a time.

Example: Write a program, to copy the content of file A into file B using Byte stream class.

Note: if there is only file A in which data is written and no file B then, file B will be create automatically.

Suppose we have a File “A”

Hello students I am aditya.  

Output: When we run above program one new file create with Name “B” and content of file “A” will be copy into file “B”.

            File “B”

Hello students I am aditya.  

Byte Streams in Java

In java programming, to perform input and output of 8-bit, Byte stream is used.

Most common byte streams classes are, FileInputStream and FileOutputStream.

FileInputStream : FileInputStream is used for reads one byte at a time .

FileOutputStream : FileOutputStream is used for writes one byte at a time

Writing Bytes

Example: Write a program, to write a bytes to a  file using Byte stream class.

Result

checking file A.txt it will show following content.

Note: If there is no file A then, file A will be create automatically

Reading bytes from a file

Suppose we have a file “A.txt”

Hello Students I am Aditya

Example: Write a program, to read a bytes from file A using Byte stream class and print on output screen.

Example: Write a program, to copy the content of file A into file B using Byte stream class.

Note: if there is only file A in which data is written and no file B then, file B will be create automatically.

Suppose we have a File “A”

Hello students I am aditya.  

Output: When we run above program one new file create with Name “B” and content of file “A” will be copy into file “B”.

File “B”

Hello students I am aditya.  

File and Input Output in Java

In Java programming, to perform the input-output in file handling  Java has a java.io package which contain contains nearly every class you might ever need.

In file handling streams represent an input source and an output destination.

Stream

In java programming, a sequence of data defined as a “stream”.

Simply  there are two type of streams:

  1. InputStream −  To read data from a source InputStream is used.
  2. OutputStream-  To write a data to a destination OutputStream is used.

Stream Classes

In java,  package “java.io”  contains a large number of stream classes and these classes can be divided into two groups:

  1. Byte stream
  2. Character stream

Thread Life Cycle in Java

Life cycle of Thread tells the various information of thread form born to terminate. Thread life cycle contains the several stages and at a time any thread can be present  in a single state.

States of Thread life cycle

  1. Born
  2. Ready
  3. Running
  4. Blocked
  5. Sleep
  6. Wait
  7. Dead
Java Thread Life Cycle
Java Thread Life Cycle

Ready:  In this state thread is ready to execute but not running. 

When the start() method calls thread enters from born to ready state.

Running:  When a run() method executes highest priority ready thread assigned a processor and enter in a running state for execution.

Thread can visit more than ones in a running state.

Blocked: When a running thread has a input-output issue it enters in a blocked state from running state and when input-output issue solves it again comes in a running thread.

Sleep : A running thread enter in a sleep state for a specified number of milliseconds when a sleep() method calls.

When sleep time expires then thread moves to ready state.

Wait : When a low priority thread executing and high priority thread comes then high priority thread get preference and enter in a running state. Then low priority thread leaves a running state and moves to wait state for indefinite time.

When a high priority thread execution completes it calls waiting thread for execution by notify () & notifyall () method.

Dead: A running thread is enter in a dead state when its execution completes (run() method completes)   or terminate for any reason.

Thread isAlive() and join() Methods in Java

There are two ways  to determine whether a thread has finished or not.

  •   isAlive()
  •   join()

isAlive():  isAlive() method is used to check whether a thread is in the running or not .

                                                or

In a another word, this method determines thread is live or dead. 

isAlive( )method returns true if the thread is still running otherwise  it returns false.

join(): This method wait for the specified thread to terminate.

Result

Thread suspend() and resume() method in Java

suspend() : This method suspend a thread for sometime but do not kill/terminate it.

resume() : This method revives the suspended thread.