0

guys i have 2 tables "employee" which has EMPID, EMPAGE, ADDRESS, SALARY, EMPNAME, department_id (foreign key refrences to table "department") and "department" table which has department_id, name ... i made a HQL query to select the departments

public List<Department> listDepartment() {
    List<Department> deps = sessionFactory.getCurrentSession()
                           .createCriteria(Department.class).list();
    return deps;
}

and i looped through the table to construct JSON object to be called by ajax request

    public void listDepartment(HttpServletResponse response) throws IOException, JSONException {
        PrintWriter out = response.getWriter();
        JSONObject obj1 = new JSONObject();
        JSONObject obj = new JSONObject();

        for(int index = 0; index<listDepartment().size(); index++){
            obj1.put("Department ID "+index,listDepartment().get(index).getDepId());
            obj1.put("Department Name "+index,listDepartment().get(index).getDepName());

            JSONArray array = new JSONArray();
            for(Employee l : listDepartment().get(index).getEmployees()){
                array.add(l.getEmpId()+" "+l.getEmpAge()+" "+l.getSalary()+" "+l.getEmpAddress());
                obj1.put("Employees "+index, array);
            }

        }

        System.out.println(obj1);
        obj.put("MyListDep", obj1);
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        out.write(obj.toString());
        out.close();

but i found the 'obj1' to be like this

{"Department Name 0":"name1","Department Name 1":"name2","Department Name 2":"name3","Department Name 3":"name4","Department Name 4":"name5","Employees 0":["1 10 salary1 address1","2 20 salary2 address2"],"Department ID 0":1,"Department ID 1":2,"Employees 2":["5 50 salary5 address5","6 60 salary6 address6"],"Employees 1":["3 30 salary3 address3","4 40 salary4 address4"],"Department ID 2":3,"Department ID 3":4,"Department ID 4":5,"Employees 4":["9 90 salary9 address9","10 100 salary10 address10"],"Employees 3":["7 70 salary7 address7","8 80 salary8 address8"]}

not preserving the order .. so i want it to print all information of index 0 then index 1 then ... etc any help ??

guido
  • 18,864
  • 6
  • 70
  • 95

0 Answers0