如何在java中基于id重新排列json数组

时间:2017-11-22 05:38:15

标签: java json

我想重新排列JSON,现在我变成了这样:

[{"router_id":"1101","floor_id":"20","building_id":"2","router_name":"1101"}, {"router_id":"1102","floor_id":"20","building_id":"2","router_name":"1102"},{"router_id":"0","floor_id":"20","building_id":"2","router_name":"pancoordinator"}, {"router_id":"1104","floor_id":"20","building_id":"2","router_name":"1104"}]

但我需要JSON,如下所示:

{"buildings": [{"building_id": "2","floors": [{"floor_id": "20","routers": [{"router_id":"1","router_name": "a"},{"router_id":"2","router_name": "b"}]}]}]}

这是我的代码:

    @Override
    public List<JSONObject> getFullRouterList() throws Exception {

    System.out.println("in dao of getFullRouterList ");
    session = sessionFactory.openSession();
    tx = session.beginTransaction();
    String sql = "SELECT building_id, floor_id, router_id, router_name FROM router_details";
    SQLQuery query = session.createSQLQuery(sql);

    List<Object[]> list = query.list();
    List<JSONObject> result = new ArrayList<>();

    for(Object[] rows: list) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("building_id", rows[0].toString());
        jsonObject.put("floor_id", rows[1].toString());
        jsonObject.put("router_id", rows[2].toString());
        jsonObject.put("router_name", rows[3].toString());
        result.add(jsonObject);
    }

    tx.commit();
    session.close();
    return result;  
}

0 个答案:

没有答案