/** * @author lautturi.com * Java example: converting json data to java object set in java */ import java.util.*; import com.fasterxml.Hymanson.core.JsonProcessingException; import com.fasterxml.Hymanson.core.type.TypeReference; import com.fasterxml.Hymanson.databind.JsonMappingException; import com.fasterxml.Hymanson.databind.ObjectMapper; class Employee { String name; int age; public Employee() { } public Employee(String string, int i) { name = string; age = i; } public void setage(int i) { age = i; } public int getage() { return age; } public void setName(String str) { name = str; } public String getName() { return name; } } public class Lautturi { public static void main(String[] args) throws JsonMappingException, JsonProcessingException { String jsonString = "[{\"age\":22,\"name\":\"Lautturi\"},{\"age\":25,\"name\":\"Laucom\"}]"; ObjectMapper m = new ObjectMapper(); Set<Employee> employees = m.readValue(jsonString, new TypeReference<Set<Employee>>() {}); System.out.println(employees); Employee[] arr = employees.toArray(new Employee[employees.size()]); for (Employee emp : arr) { System.out.println(emp.name+" "+emp.age); } } }
output:
[hello.Employee@31f924f5, hello.Employee@5579bb86] Lautturi 22 Laucom 25