How to Parse JSON Array With Gson

Parsing JSON array is very easy with Gson.

Follow these steps to read JSON Array

  1. Create GSON Object
  2. Read array with fromJson()

To read jsonString as array we use following syntax

Gson gson=new Gson();
ElementType [] refVar=gson.fromJson(jsonString,ElementType[].class);

To read jsonString as List TypeToken is used to find the type of class

List eList=(List)gson.fromJson(reader, new TypeToken>(){}.getType());
List employeeList=(List)gson.fromJson(reader, new TypeToken>(){}.getType());

Here ElementType is Empolyee so we read data as below

Employee [] employees = gson.fromJson(reader, Employee[].class);

JSON Array is below. It is stored in server to read this URL is used

Employee.java

This is simple Java bean containing get and set methods.

The employee class should have same filed name as in JSON. Field name in JSON should match with field name with Employee class.

ReadEmployee.java

This file contains main method.

To read data from URL URL class and HTTPURLConnection is used.

To read data Gson Object is created and fromJson() is used.

fromJson() parse json string and store in array of Employee.

Result

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

JSON Tutorial Basic to Advance

JSON stand for Java Script Object Notation (JSON).

JSON is not a Programming Language. JSON is a data interchange format.

Using JSON we can transfer data between client and server and server to server.

JSON is defined in RFC4627 written in 2006. Internet Engineering Task Force (IETF) published JSON RFC7159 in March 2014.

Later on standard updated on RFC8259 and EMCA 404

JSON media type(MIME type) is application/json

JSON file extension is <code>.json</code>

In JSON data can be in following structure

  • A collection of name/value pair
  • An ordered list of value

These two are the universal data structure supported by approx all programming languages. So data exchange between one language to another is easy by JSON.

JSON string example is as below

Why use JSON?

As JSON format is text only, it can be sent to server and also can received from a server, and also can be used as a data format by any programming language.

If you receive data from a server, in JSON format, you can use it like any other JS object.

JSON Syntax

JSON syntax is derived from JS object notation syntax.

•        Data is in name/value pairs

•        Curly braces hold objects

•        Data is separated by commas

•        Square brackets hold arrays

JSON Data

JSON data is written as name or value pairs.

A name or value pair consists of a field name like this “”, and it will follow by a colon, and also followed by a value:

Example

{“name”:”Ayan” }

JSON – Evaluates to JS Objects

The JSON format is a also JavaScript objects.

In JSON, keys must be strings, written with double quotes:

JSON

{ “name”:”Ayan” }

In JSON, keys can be strings, numbers, or identifier names,

{ name:”Ayan” }

JSON with JavaScript Syntax

JSON syntax is derived from JavaScript object notation, very little extra software is needed to work with JSON within JS.

With JS you can create an object and assign data to it.

Example

Access a JavaScript object

Result

Ayan

produce the same output as above

JSON Values

In JSON, values must be one of the following data types:

  •   a string 
  •   a number
  • an object
  •   an array

or one of the following literal names

  • false
  • true
  • null
JSON Value
Fig : JSON Value

JSON String Value

String value is represented in quotation any unicode character is used to create string.

like

” ” //empty string
“Ram” //string value
“\”” // use of escape character
“\uXXXX” // unicode value

JSON Numbers

 JSON allows numbers as an integer or a floating point numbers.

Example

25
24.25
3.55
3.1e3

JSON Objects

Values in JSON can be objects. It contains zero or more name value pairs in curly braces seperated by comma

Example

{
“employee”:{ “name”:”Ayan”, “age”:25, “city”:”Mumbai” }
}

JSON Array

JSON Array are surrounded by [ (squrae bracket) and zero or more values or elements are seperated by comma.

The values in array may be of different types.

Example

[“red’,”blue”,”green”, “orange”]

A composite JSON structure is also possible

Here a JSON array contains two objects and each object contains string, number and array values

JSON is purely a data format — it contains only properties, no methods.

  • JSON need a double quotes to be used around strings and property names. Single quotes are not valid in a JSON.
  • A single misplaced colon or comma can cause a JSON file to go wrong, and not working that JSON file. Always be careful to validate any data in JSON. A validate JSON using an application like JSONLint.
  •    JSON can be taken the form of any data type that is valid for inside JSON, not just arrays or objects. So, a single string or a number can be a valid JSON object.
  • Unlike in JavaScript code in which object properties may be unquoted, in JSON, only quoted strings may be used as properties.

Converting between objects and textSection

In JSON can be set the XHR request to convert the JSON response directly into a JS object using:

request.responseType = ‘json’;

But sometimes can be receive a raw JSON string, and  need to convert it to an object.

when try to send a JavaScript object across the network, then need to convert it to JSON (a string) before sending.

These two problems are so common that a built-in JSON object is available, which contains the following two methods:

  • parse(): Accepts a JSON string as a parameter, and returns the corresponding JavaScript object.
  • stringify(): Accepts an object as a parameter, and returns the equivalent JSON string form.

See one example of stringify()

{“name”:”Ram”,”age”:24,”mailIds”:[“[email protected]”,”[email protected]”,”[email protected]”]}

console.table(obj); prints array in tabular format
console.log(obj[0].name); print first objects name
for (var row in obj) will iterate each object and access its properties in name value pair

Example

Sam Ghosh

JSON.parse()

A common use of JSON is to exchange data to/from a web server.

parse() is used to convert JSON data to JavaScript values

Server send data as a string. To convert this string to JavaScript object  JSON.parse() method is used

Example – Parsing JSON

This text received from a web server:

‘{ “name”:”Ayan”, “age”:25, “city”:”Mumbai”}’

Use the JavaScript function JSON.parse() to convert text into a JavaScript object:

varobj = JSON.parse(‘{ “name”:”Ayan”, “age”:25, “city”:”Mumbai”}’);

Use the JavaScript function JSON.parse() to convert text into a JavaScript object:

Example

Create Object from JSON String

Ayan, 25

How to access nested JSON objects

Bajaj Bajaj

JSON Arrays

EXAMPLE

Access an array value of a JSON object

Honda

EXAMPLE

Looping through an array using a for in loop

Honda Bajaj Hero

EXAMPLE

Looping through arrays inside arrays

Nested JSON Objects

Honda Hornet xblade livo Bajaj pulsar neon X5 Hero 500 Panda

See one Example to read JSON data and show in console

Result

Console.table()
Fig: Console.table()

JSON Vs XML

Extensible Markup Language(XML) is a Markup Language.

XML is used to access and transfer the data same like JSON.

XML uses tag to wrap content.

General structure of XML to send send data is as below

For above data JSON is

XML and JSON both are data interchange format.

In XML we have to add additional tags to carry data that is not is JSON no overhead required to carry data in JSON

JSON is based on JavaScript. XML is derived from SGML.

JSON can use Array and objects to represent and carry data. XML uses markup structure to carry data

JSON uses key value pair and array object that allows direct mapping of data structure of appropriate language.

XML allows namespace to avoid name conflicts this is not available in JSON.

JSON Formatter and Validator

JSON Formatter are used to provide structure way to JSON data.

JSON validators are tool that are used to validate JSON data.

Why JSON formatter and validator required.

If you get data from server it is in unformatted way

Like I get JSON data from url

api.openweathermap.org/data/2.5/weather?q=London

This will provide me weather information of London

JSON response from api.openweathermap.org
FIg: JSON response from api.openweathermap.org

Above JSON data is difficult to read we have to format above data to make it readable.

Few online tools that can be used are

JSONLint – The JSON Validator

JSON Formatter & Validator

and many more

put code received from URL to any one validator that validate and structure the data so that it can be readable

Formatted JSON from api.openweathermap.org
Fig: Formatted JSON from api.openweathermap.org

Bootstrap Clearfix

Bootstrap float utility is very helpful in positioning the components properly on the web-page.

But there are is an issue in this approach that needs to be addressed. Check out the code below to know about the same:

If you load this code on a browser, you can observer following points:

  • A <div> is created with a green border and some text content in it
  • The <img> added to this <div> is made to float to the right of the div
  • The image is overflowing from the <div> component

The third point is the float issue we were talking about.

When you make any element to float, it might flow around its containing element.

This is bad for the styling on the webpage as the components not look very neat.

To fix this problem we have special hack in Bootstrap called the ‘clearfix’ hack.

Here we will understand what the ‘Clearfix’ hack is and how it can help us to solve the problem we discussed before.

Clearfix Hack

Basically clearfix, clears the overflowing float component.

You can add the clearfix to the containing element (like the <div> in this case) and will contain the floating element withing itself so it doesn’t overflow.

The code below explains how you can use clearfix in CSS. Based on this knowledge, we will understand how we can use clearfix in Bootstrap.

Now that, we have understood the basic working of a clearfix, let’s move to Bootstrap.

Bootstrap Clearfix Utilities

So, we know that Clearfix quickly and easily clears the floated content within a container.

The basic classe used for this is the .clearfix. This is used with the parent element.

You can also use clearfix with Mixins

// Mixin itself

Check the code snippet below to understand how clearfix can be used in Bootstrap in a typical webpage

Exception Handling in Java with Examples

Exception Handling in java

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

What is an Exception in Java

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

Arithmetic Exception Example

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.

NumberFormatException Handling

>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.

Multiple catch blocks java

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.

 Which of the following is not an advantage of Java exception handling?

 A. Java separates exception handling from normal processing tasks.
 B. Exception handling improves performance.
 C. Exception handling makes it possible for the caller’s caller to handle the exception.
 D. Exception handling simplifies programming because the error-reporting and error-handling code can be placed at the catch block.

Answer is B

More MCQ

Read More

  1. Exception Handling in Java: Hierarchy Example and Types
  2. Exception Handling try catch finally blocks in Java
  3. Throw and Throws Keywords in Java
  4. How To Fix Internal Exception: java.io.ioexception In Minecraft