Sunday, 19 April 2020

Gson: Convert json to a typed array list

Using TypeToken, you can convert a json to typed array list.

Example
Type type = new TypeToken<List<Employee>>() {}.getType();
List<Employee> deserializedEmps = gson.fromJson(json, type);

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;
import java.lang.reflect.Type;
import com.google.gson.reflect.TypeToken;

public class App {

 public static void main(String args[]) throws ClassNotFoundException {
  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);

  Type type = new TypeToken<List<Employee>>() {}.getType();

  List<Employee> deserializedEmps = gson.fromJson(json, type);

  for (Employee emp : deserializedEmps) {
   System.out.println(emp);
  }
 }
}

Output
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