I want to rearrange the JSON, now i am getting like this:
[{"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"}]
But i need JSON like following one:
{"buildings": [{"building_id": "2","floors": [{"floor_id": "20","routers": [{"router_id":"1","router_name": "a"},{"router_id":"2","router_name": "b"}]}]}]}
This is my code:
@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;
}
https://github.com/octomix/josson
List<Object[]> list = query.list();
ObjectMapper mapper = new ObjectMapper();
ArrayNode array = mapper.createArrayNode();
for(Object[] rows: list) {
ObjectNode object = mapper.createObjectNode();
object.put("building_id", rows[0].toString());
object.put("floor_id", rows[1].toString());
object.put("router_id", rows[2].toString());
object.put("router_name", rows[3].toString());
array.add(object);
}
Josson josson = Josson.create(array);
JsonNode node = josson.getNode(
"group(building_id).map(" +
" building_id," +
" floors: elements.group(floor_id).map(" +
" floor_id," +
" routers: elements.map(" +
" router_id, router_name)" +
" )" +
")" +
".toObject('buildings')");
System.out.println(node.toPrettyString());
Output
{
"buildings" : [ {
"building_id" : "2",
"floors" : [ {
"floor_id" : "20",
"routers" : [ {
"router_id" : "1101",
"router_name" : "1101"
}, {
"router_id" : "1102",
"router_name" : "1102"
}, {
"router_id" : "0",
"router_name" : "pancoordinator"
}, {
"router_id" : "1104",
"router_name" : "1104"
} ]
} ]
} ]
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.