Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting list to JSON [duplicate]

Tags:

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"]}
like image 946
harsh Avatar asked Sep 14 '17 08:09

harsh


1 Answers

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();
    }
like image 141
Punit Avatar answered Sep 22 '22 11:09

Punit