我一直在開發Spring Boot REST API。除了我的問題,我迄今爲止做了很多事情。我正在使用springfox swagger UI進行文檔編制,並將模型和dtos分開以獲得更好的結構。如何將http狀態添加到所有響應dto(數據傳輸對象)?
我有一個基地DTO模式:
public class BaseDto {
private int code;
private boolean success;
public BaseDto() {
this.code = HttpStatus.OK.value();
this.success = HttpStatus.OK.is2xxSuccessful();
}
}
當然,我使用這個類通過擴展它像:
@ApiModel("User")
public class UserDto extends BaseDto {
private String email;
private String username;
// stuffs
}
如果我做用戶請求當我使用這種結構時,我得到:
{
code: 200,
success: true,
email: "",
username: ""
}
等等......這很好,但在其他dtos中,像post模型,我有UserDto列表,它以這種形式顯示。在每個對象中,都會寫入「代碼」和「成功」字段;然而,這不是我想要的。
我希望實現的目標只有一次「代碼」和「成功」寫入響應JSON主體而不是所有返回列表對象。
爲了澄清更多,這是郵政DTO模式和收益是這樣的:
{
"code": 0,
"createdAt": "2016-05-17T21:59:37.512Z",
"id": "string",
"likes": [
{
"code": 0,
"createdAt": "2016-05-17T21:59:37.512Z",
"deviceType": "string",
"email": "string",
"fbAccessToken": "string",
"fbId": "string",
"followers": [
{}
],
"followings": [
{}
],
"id": "string",
"profileImage": "string",
"success": true,
"token": "string",
"udid": "string",
"updatedAt": "2016-05-17T21:59:37.512Z",
"username": "string",
"version": 0
}
],
"pictures": [
"string"
],
"postedBy": {
"code": 0,
"createdAt": "2016-05-17T21:59:37.512Z",
"deviceType": "string",
"email": "string",
"fbAccessToken": "string",
"fbId": "string",
"followers": [
{}
],
"followings": [
{}
],
"id": "string",
"profileImage": "string",
"success": true,
"token": "string",
"udid": "string",
"updatedAt": "2016-05-17T21:59:37.512Z",
"username": "string",
"version": 0
},
"success": true,
"text": "string",
"updatedAt": "2016-05-17T21:59:37.512Z",
"userId": "string",
"userIds": [
"string"
],
"version": 0
}
您可以在郵政DTO模式看到用戶DTO使用,代碼和成功字段添加多餘的。
我不知道最可能我得到了錯誤的方法。也許,我應該爲所有返回的DTO添加全局HTTP狀態響應。
任何人都可以幫忙嗎?
你能解決這個@saxahan嗎? – Sampada