Map的订单输出

时间:2016-08-21 12:59:03

标签: java json hashmap

编写REST API,请求和响应是Json。我把json的响应作为Map,并想知道为什么它在屏幕上的输出不是按顺序我做的? 我的控制器的示例代码,我在其中构建Map:

@ExceptionHandler(ApiErrorNotFound.class)
@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;
}

,输出为:

{
  "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"
}

2 个答案:

答案 0 :(得分:1)

要保留订单,请尝试使用LinkedHashMap

答案 1 :(得分:1)

HashMap的迭代顺序不能保证与插入顺序相同。

如果要在迭代时保留插入顺序,请查看:

LinkedHashMap