Step 1: Instantiate Genson object
Genson
genson = new Genson();
Step 2: Use following snippet to conver json to list of
objects.
public
List<T> getListOfObjects(String json, GenericType<List<T>>
list) {
return genson.deserialize(json, list);
}
public class Employee { private String id; private String firstName; private String lastName; private String password; public String getId() { return id; } public void setId(String 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; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("Employee [id=").append(id).append(", firstName=") .append(firstName).append(", lastName=").append(lastName) .append(", password=").append(password).append("]"); return builder.toString(); } }
import java.util.List; import com.owlike.genson.GenericType; import com.owlike.genson.Genson; public class JSONUtil<T> { private static Genson genson = new Genson(); public static String getJson(Object obj) { return genson.serialize(obj); } public T deserializeJson(String json, Class<T> clazz) { return genson.deserialize(json, clazz); } public List<T> getListOfObjects(String json, GenericType<List<T>> list) { return genson.deserialize(json, list); } }
import java.util.ArrayList; import java.util.List; import com.owlike.genson.GenericType; public class Test { public static void main(String args[]) { Employee emp1 = new Employee(); Employee emp2 = new Employee(); Employee emp3 = new Employee(); emp1.setId("E432156"); emp1.setFirstName("Hari krishna"); emp1.setLastName("Gurram"); emp1.setPassword("Password123"); emp2.setId("32452"); emp2.setFirstName("Senthi"); emp2.setLastName("Kumaran"); List<Employee> emps = new ArrayList<>(); emps.add(emp1); emps.add(emp2); emps.add(emp3); JSONUtil<Employee> util = new JSONUtil<Employee>(); String json = JSONUtil.getJson(emps); System.out.println("Json is "); System.out.println(json); List<Employee> empsTmp = util.getListOfObjects(json, new GenericType<List<Employee>>() { }); System.out.println("\nAfter deserialization"); System.out.println(empsTmp); } }
Output
Json is [{"firstName":"Hari krishna","id":"E432156","lastName":"Gurram","password":"Password123"},{"firstName":"Senthi","id":"32452","lastName":"Kumaran","password":null},{"firstName":null,"id":null,"lastName":null,"password":null}] After deserialization [Employee [id=E432156, firstName=Hari krishna, lastName=Gurram, password=Password123], Employee [id=32452, firstName=Senthi, lastName=Kumaran, password=null], Employee [id=null, firstName=null, lastName=null, password=null]]
No comments:
Post a Comment