I am receiving a following list from DB which I want to convert to JSON:
Employee e1=new Employee(101,"Ha","De","Acr");
Employee e2=new Employee(102,"D ","Forouzan","Mc");
Employee e3=new Employee(102,"Op","Ga","Wi");
Employee e4=new Employee(101,"YUI","HI","EX");
I want to change it just it tranverses the above received list and for duplicate keys (101, 102) it creates one jsoobject using array;
ex: 101 : {["Ha","De","Acr"],["YUI","HI","EX"]}
I tried the below one and got the expected result :
public static void main(String[] args) {
Employee e1 = new Employee(101, "Ha", "De", "Acr");
Employee e2 = new Employee(102, "D ", "Forouzan", "Mc");
Employee e3 = new Employee(102, "Op", "Ga", "Wi");
Employee e4 = new Employee(101, "YUI", "HI", "EX");
List<Employee> employeeList1 = new ArrayList<>();
employeeList1.add(e1);
employeeList1.add(e4);
List<Employee> employeeList2 = new ArrayList<>();
employeeList2.add(e2);
employeeList2.add(e3);
Map<Integer, ArrayList<Employee>> map = new HashMap<Integer, ArrayList<Employee>>();
// As of now , I have populated the map directly, but you can place some logic here for putting the values here dynamically.
map.put(101, (ArrayList<Employee>) employeeList1);
map.put(102, (ArrayList<Employee>) employeeList2);
ObjectMapper mapper = new ObjectMapper();
try {
String json = mapper.writeValueAsString(map);
System.out.println(json);
} catch (JsonProcessingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With