SpringMVC篇: 入參出參通過JsonProperty屬性轉換

工作中會遇到和前端對接的相關事宜,很多時候可能是並行開發,但是很多時候這個數據結構到底是前端定義還是後端給出一直有點模糊不清。

問題:

  1. 如果是前端定義,後端把接口開發完成之後,發現數據和你的名稱對不上,可能需要進行格式轉換,比較麻煩,作爲後端人員可能會比較排斥。
  2. 如果是後端定義: 前端各種催,接口出來了沒,我要對接了。

其實從效率上來講,應該是前端來定義數據結構文檔,會比較快捷。

這裏其實SpringMvc中有提供特定的註解來完成。入參和出參均可。

@JsonProperty

場景代碼演示

@ApiOperation(value = "測試用的", nickname = "liukx")
@RequestMapping(value = "/test", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
public ObjectResponseModel<MvpTestResponse> test(@RequestBody @Valid ValidateLoginVCRequest request) throws Exception {
    MvpTestResponse mvpTestResponse = new MvpTestResponse();
    mvpTestResponse.setTest1("aaaaaaaaaa");
    return ResponseUtils.trueObj(mvpTestResponse);
 }

定義一個路由,入參爲MvpTestRequest對象,出參爲MvpTestResponse對
MvpTestRequest

import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import org.hibernate.validator.constraints.NotEmpty;

@ApiModel(description = "xxxx")
public class MvpTestRequest{
  
	// 這裏是對外的屬性暴露.
   	@JsonProperty(value = "testName", defaultValue = "123")
    @ApiModelProperty(name = "testName", value = "測試名稱", example = "123456", required = true)
    private String test;
    // get set ...
}

MvpTestResponse

@ApiModel(description = "測試用的")
public class MvpTestResponse {

    @ApiModelProperty(name = "testResponse", value = "test1")
    @JsonProperty(value = "testResponse")
    public String test1;
    // get set ...
}

從swagger中來看入參
swagger 入參

swagger出參
結果描述
這時候後端只需要在對應的入參出參中通過@JsonProperty實現和前端的數據結構進行匹配。

發佈了28 篇原創文章 · 獲贊 13 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章