如何创建嵌套的JSON响应

时间:2018-10-02 17:22:31

标签: java json spring-boot

我正在使用spring-boot来处理异常并返回时间戳,消息和详细信息。

我的异常类如下:

enter image description here

我的JSON响应是:

enter image description here

我的问题是,如何退货:

Exception: {
    "timestamp": "2018-10-02T17:07:31.095+0000",
    "message": "id: 45267",
    "details": "uri=/v1/users/45267"
}

1 个答案:

答案 0 :(得分:2)

JSON格式直接映射到相应的Java类设计。
在您的情况下,以下声明可以-

class ExceptionResponse {
    private CustomException exception;
}
class CustomException {
    private Date timestamp;
    private Message message; //can even split message further.
    private String details;
}

class Message {
    private int id;
    private String category;
    private String comment;
}

ExceptionResponse的输出JSON为:

exception: {
    "timestamp":"...",
    "message": {
          "id":"...",
          "category":"...",
          "comment":"..."
    },
    "details":"..."
}