Tuesday 1 October 2019

Gson: Convert json to an array


We have a json string like below.
[
  {
    "id": 1,
    "firstName": "Ravindra",
    "lastName": "Gidugu"
  },
  {
    "id": 2,
    "firstName": "Rahim",
    "lastName": "Khan"
  },
  {
    "id": 3,
    "firstName": "Joel",
    "lastName": "Chelli"
  },
  {
    "id": 4,
    "firstName": "Ram",
    "lastName": "GUrram"
  }
]

Below statement convert the json string to an array.
Employee[] deserializedEmps = gson.fromJson(json, Employee[].class);

Find the below working application.

Employee.java
package com.sample.app.model;

public class Employee {
 private int id;

 private String firstName;
 private String lastName;

 public Employee() {

 }

 public Employee(int id, String firstName, String lastName) {
  super();
  this.id = id;
  this.firstName = firstName;
  this.lastName = lastName;
 }

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public String getFirstName() {
  return firstName;
 }

 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }

 public String getLastName() {
  return lastName;
 }

 public void setLastName(String lastName) {
  this.lastName = lastName;
 }

 @Override
 public String toString() {
  return "Employee [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + "]";
 }

}


App.java
package com.sample.app;

import java.util.Arrays;
import java.util.List;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.sample.app.model.Employee;

public class App {

 public static void main(String args[]) {
  Employee emp1 = new Employee(1, "Ravindra", "Gidugu");
  Employee emp2 = new Employee(2, "Rahim", "Khan");
  Employee emp3 = new Employee(3, "Joel", "Chelli");
  Employee emp4 = new Employee(4, "Ram", "GUrram");
  
  List<Employee> emps = Arrays.asList(emp1, emp2, emp3, emp4);
  
  Gson gson = new GsonBuilder().setPrettyPrinting().create();
  
  String json = gson.toJson(emps);
  
  System.out.println(json);
  
  Employee[] deserializedEmps = gson.fromJson(json, Employee[].class);
  for(Employee emp : deserializedEmps) {
   System.out.println(emp);
  }
 }
}


Output
[
  {
    "id": 1,
    "firstName": "Ravindra",
    "lastName": "Gidugu"
  },
  {
    "id": 2,
    "firstName": "Rahim",
    "lastName": "Khan"
  },
  {
    "id": 3,
    "firstName": "Joel",
    "lastName": "Chelli"
  },
  {
    "id": 4,
    "firstName": "Ram",
    "lastName": "GUrram"
  }
]
Employee [id=1, firstName=Ravindra, lastName=Gidugu]
Employee [id=2, firstName=Rahim, lastName=Khan]
Employee [id=3, firstName=Joel, lastName=Chelli]
Employee [id=4, firstName=Ram, lastName=GUrram]




Previous                                                    Next                                                    Home

No comments:

Post a Comment