2016-05-17 88 views
0

我一直在開發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狀態響應。

任何人都可以幫忙嗎?

+0

你能解決這個@saxahan嗎? – Sampada

回答

0

你可以有一個AppUtil類,你可以創建你的迴應並設置HttpStatus。在你AppUtil類寫一個方法,像這樣:

public static ResponseEntity<ResponseEnvelope> successResponse(Object data, 
     int messageCode, String message) { 
    ResponseEnvelope envelope = new ResponseEnvelope(data, true, message, 
      messageCode); 
    ResponseEntity<ResponseEnvelope> responseEntity = new ResponseEntity<>(
      envelope, HttpStatus.OK); 
    return responseEntity; 
} 

successResponse方法,你可以設置你的data對象,其中與HttpStatus一起將要返回ResponseEntity發送的ResponseEnvelope

查看我之前的回答here

+0

謝謝你的回答。我會將所有的api調用都轉換爲ResponseEntity,但它仍然沒有嵌入返回Json的http狀態字段。我怎麼能這樣做? – saxahan

+0

使用HttpStatus獲取statusCode statusCode = responseEntity.getStatusCode();否則,你將不得不明確地添加你的json。 –

相關問題