Use Swagger/OpenAPI discriminator so that Jackson serializes object correctly

天涯浪子 提交于 2019-12-10 16:40:09

问题


We're having trouble using the OpenAPI 2.0 discriminator in way that makes both the Swagger tools and the Jackson serializer happy.

Problem: during serialization Jackson currently generates two JSON properties for the discriminator, one of them having a null value.

OpenAPI 2.0 definition

swagger: '2.0'
info:
  version: v1
  title: Error API
paths:
  /errors:
    get:
      description: Stack Overflow test
      responses:
        '200':
          description: OK
          schema:
            $ref: '#/definitions/SpecificError'
definitions:
  GeneralError:
    description: Error Base Structure
    type: object
    discriminator: errorType
    properties:
      errorType:
        type: string
      message:
        type: string
    required: 
      - errorType
  SpecificError:
    description: Test
    allOf: 
      - $ref: "#/definitions/GeneralError"

AFAIU the discriminator is correctly defined. The spec requires it to be listed both in the properties and the required list.

The property name used MUST be defined at this schema and it MUST be in the required property list. When used, the value MUST be the name of this schema or any schema that inherits it.

Swagger codegen

What the Swagger Java codegen produces is this:

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "errorType",
    visible = true)
@JsonSubTypes({
    @JsonSubTypes.Type(value = SpecificError.class, name = "SpecificError"),
})

public class GeneralError {
    @JsonProperty("errorType")
    private String errorType = null;
    // accessors, even for errorType!, follow here

The accessors for errorType come as a big surprise. As the field is only needed during serialization & deserialization regular client code shouldn't have access to it. One could even argue that the field shouldn't be there at all.

Jackson serializer

As a simple test bed I use this

SpecificError specificError = (SpecificError) new SpecificError().message("message")
ObjectMapper objectMapper = new ObjectMapper();
ObjectWriter writer = objectMapper.writer();
writer.writeValue(System.out, specificError);

This produces {"errorType":"SpecificError","message":"message","errorType":null}.

-> errorType appears twice

Q: whose fault is it? Is my Swagger definition wrong? Should the Swagger Java codegen not generate private String errorType? Or should Jackson be able to deal with this i.e. recognize that its @JsonTypeInfo and the property of that name are actually the same thing?

来源:https://stackoverflow.com/questions/50163882/use-swagger-openapi-discriminator-so-that-jackson-serializes-object-correctly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!