【发布时间】:2019-08-23 06:06:10
【问题描述】:
在 Rest 响应中,我的 swagger 文件中标记为“鉴别器”的字段被复制。我有一个父对象,它有一个名为“subjectType”的字段,我已将其标记为鉴别器。在我的休息调用中,我只返回资源对象(SubjectA 对象或 SubjectB 对象基于请求中的 subjectType),它具有以下 swagger 文件中提到的所有参数:
Subject:
type: object
discriminator: subjectType
properties:
id:
type: string
minLength: 32
maxLength: 32
description:
type: string
maxLength: 350
subjectType:
type: string
enum:
- SubjectA
- SubjectB
required:
- subjectType
- description
SubjectA:
allOf:
- $ref: "#/definitions/Subject"
- type: object
properties:
name:
type: string
maxLength: 100
complexity:
type: string
maxLength: 256
required:
- name
- complexity
SubjectB:
allOf:
- $ref: "#/definitions/Subject"
- type: object
properties:
prof:
type: string
maxLength: 100
ref:
type: string
maxLength: 256
required:
- prof
- ref
所以,当我返回 SubjectA 或 SubjectB 类型的响应对象时,我发回的响应对象只有一个“subjectType”字段,但实际的 json返回给客户端的响应有两个“subjectType”字段,我认为这是招摇的。 Swagger 版本:2.4.1
回复如下:
{ "subjectType" : "SubjectA", “id”:“123”, "subjectType" : "SubjectA", “名称”:“abc”, “复杂性”:“L1” }
@Path("/subjects")
@POST
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
@ResponseStatus(status = Response.Status.CREATED)
public Response createSubject(Subject subject) {
//Removed my DAO calls and other logic.
final Subject subject =
createSubject(profile); //Modifying the subject object in this method as per my needs.
return Response.status(Response.Status.CREATED).entity(subject).build();
}
以下是swagger codegen生成的对象:
@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2019-04-01T17:05:27.110-07:00")@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "subjectType", visible = true )
@JsonSubTypes({
@JsonSubTypes.Type(value = SubjectA.class, name = "SubjectA"),
@JsonSubTypes.Type(value = SubjectB.class, name = "SubjectB"),
})
public class Subject {
@JsonProperty("id")
private String id;
@JsonProperty("description")
private String description;
@JsonProperty("subjectType")
private String subjectType;
//Getters and Setters
}
@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2019-04-01T17:05:27.110-07:00")
public class SubjectA extends Subject {
@JsonProperty("name")
private String name;
@JsonProperty("complexity")
private String complexity;
//Getter and Setters
}
如何阻止 subjectType 字段在发送回客户端的 Json 响应中填充两次?
【问题讨论】:
-
1) 您有
discriminator: type但主题架构中没有type属性。它应该是discriminator: subjectType吗? 2)您在服务器端使用什么库/框架来产生响应?您可以发布发送有问题响应的端点的代码吗? -
@Helen 1. 你说得对,鉴别器是 subjectType (这是一个错字,我现在编辑了我的问题)。 2. 我们使用 Jersey(Jax-rs 实现)。我现在已将代码 sn-ps 添加到我的问题中。请在上面查看。
-
谢谢海伦,这篇文章Duplicate JSON Field with Jackson 为我工作。我已将 @JsonTypeInfo 注释更改为 JsonTypeInfo.As.EXISTING_PROPERTY 而不是 JsonTypeInfo.As.PROPERTY。
-
@AlfaRomeo 是否使用生成的类,每次新生成后都更改?
标签: java rest jax-rs yaml swagger