zzheads zzheads - 2 months ago 6x
Java Question

Order output of Map

Writing REST API, requests and responses are Json. I make json responses as Map and wondering why its output on screen not in order I've made it?
Example code of my controller, where I construct Map:

@ResponseStatus(value = HttpStatus.NOT_FOUND)
public @ResponseBody Map handleDaoException(HttpServletRequest req, ApiErrorNotFound exc) {
Map<String, String> res = new HashMap<>();
Date date = new Date();
res.put("timestamp", String.valueOf(new Timestamp(date.getTime())));
res.put("status", String.valueOf(exc.getStatus()));
res.put("error", "Not Found");
res.put("exception", ApiErrorNotFound.class.getName());
res.put("message", exc.getMessage());
res.put("path", req.getServletPath());
return res;

and output is:

"exception": "com.zzheads.HomeAutomation.exceptions.ApiErrorNotFound",
"path": "/room/9",
"error": "Not Found",
"message": "Can't find room with 9 id. (com.zzheads.HomeAutomation.controller.RoomController.getRoomById(RoomController.java:63))",
"timestamp": "2016-08-21 15:49:01.961",
"status": "404"


The iteration order of HashMap is not guaranteed to be same as the insertion order.

If you want to keep the insertion order when iterating, look at: