Home » json » How to Parse JSON Array With Gson

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

Please follow and like us:
error