我正在使用Spring-boot开发API,并且文档是使用RestDocs完成的。但是,我正在测试Swagger。
我大摇大摆地发现了记录API方法响应的问题。
我有一个名为Response的对象,这是我返回响应的ResponseEntity类型。例如:
@RequestMapping(method = RequestMethod.POST, produces = "application/json")
@ApiOperation(value = "Add a new Resource")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Successful operation"),
@ApiResponse(code = 400, message = "Bad Request")
@ApiResponse(code = 500, message = "Internal Server Error")
})
ResponseEntity<Response> createResource(Resource resource){
// ...
try{
// ...
return ResponseEntity.ok(new Response().addObject("resource", resource));
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(new Response().addObject("error", "can't process request"));
}
}
响应对象:
public class Response {
private HashMap<String, Object> response = new HashMap<>();
public Response() {
reset();
}
public HashMap<String, Object> getResponse() {
return response;
}
public Response addObject(String key, Object object) {
response.put(key, object);
return this;
}
public Response reset() {
response.clear();
response.put("timestamp", new Date());
return this;
}
}
资源:
@Entity(name = "resource")
@Table(name = "resource")
@TypeDef(name = "jsonb", typeClass = JsonBinaryType.class)
@ApiModel(value = "Resource", description = "A resource")
public class Resource {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(columnDefinition = "serial")
@ApiModelProperty(notes = "The database generated loyappty ID", readOnly = true)
private Integer id;
@NotNull
@ApiModelProperty(notes = "Resource name", required = true)
private String name;
@Type(type = "jsonb")
@Column(columnDefinition = "jsonb")
@NotNull
@ApiModelProperty(notes = "Resource name", required = true)
private Map<String, Object> info = new HashMap<>();
//...
//Getters, Setters & other methods
// ...
}
问题在于Swagger没有正确记录答案。
image here with Swagger response doc
这是真实的答案:
{
"response" : {
"resource" : {
"id" : 1,
"name" : "Dummy resource",
"info" : {
"type" : "X",
"owner" : "me"
}
},
"timestamp": "2018-11-28T20:01:51.663+0000"
}
}
我认为我的困惑是我的Response对象实际上包含一个HashMap,而Swagger不知道该HashMap包含什么。在这种情况下,地图将包含:
<“资源”,资源>,<“时间戳”,日期>
您知道可能会发生什么或如何解决吗?
你能帮我吗?谢谢。