工作中會遇到和前端對接的相關事宜,很多時候可能是並行開發,但是很多時候這個數據結構到底是前端定義還是後端給出一直有點模糊不清。
問題:
- 如果是前端定義,後端把接口開發完成之後,發現數據和你的名稱對不上,可能需要進行格式轉換,比較麻煩,作爲後端人員可能會比較排斥。
- 如果是後端定義: 前端各種催,接口出來了沒,我要對接了。
其實從效率上來講,應該是前端來定義數據結構文檔,會比較快捷。
這裏其實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中來看入參
這時候後端只需要在對應的入參出參中通過@JsonProperty
實現和前端的數據結構進行匹配。