Swagger 定义未按预期显示

Swagger definition not displaying as expected

我有以下代码,但 swagger 并没有像我期望的那样显示 swagger ui。我正在使用注释来 build 大摇大摆的定义。我尝试使用@API 和@JsonIgnore。两者都不适合我。

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
import io.swagger.annotations.Api;


@JacksonXmlRootElement(localName = "traction")
@Api(hidden = true)
public class Traction
{
  private JsonNode traction;

  public JsonNode getTraction()
  {
    return traction;
  }

  public void setTraction(final JsonNode traction)
  {
    this.traction = traction;
  }

}

Swagger 定义显示如下 -

"tractionParent": {
    "traction": {
      "array": false,
      "null": false,
      "float": false,
      "containerNode": false,
      "missingNode": false,
      "nodeType": "ARRAY",
      "valueNode": false,
      "object": false,
      "pojo": false,
      "number": false,
      "integralNumber": false,
      "short": false,
      "int": false,
      "long": false,
      "double": false,
      "bigDecimal": false,
      "bigInteger": false,
      "textual": false,
      "boolean": false,
      "binary": false,
      "floatingPointNumber": false
    }
  }

我需要它显示为

"tractionParent": {
    "traction": {
     }
 }

您已经采用了 'traction' 变量类型 JsonNode,这就是您获取 Class com.fasterxml.jackson.databind.JsonNode 的所有属性的原因。 有关详细信息,请访问 link JsonNode Class 查看源代码

我最近遇到了同样的问题,并通过注册自定义 ModelConverter 解决了这个问题,该自定义 ModelConverterJsonNode 映射到 free form object for swagger

class JsonNodeProperty extends AbstractProperty {
    protected boolean additionalProperties = true;

    public JsonNodeProperty() {
        setType("object");
    }

    public boolean isAdditionalProperties() {
        return additionalProperties;
    }

    public void setAdditionalProperties(boolean additionalProperties) {
        this.additionalProperties = additionalProperties;
    }
}

class JsonNodeModelConverter implements ModelConverter {
    @Override
    public Property resolveProperty(Type type, ModelConverterContext context, Annotation[] annotations, Iterator<ModelConverter> chain) {
        JavaType javaType = Json.mapper().constructType(type);
        if (javaType != null) {
            Class<?> clazz = javaType.getRawClass();
            if (JsonNode.class.isAssignableFrom(clazz)) {
                return new JsonNodeProperty();
            }
        }
        if (chain.hasNext()) {
            return chain.next().resolveProperty(type, context, annotations, chain);
        } else {
            return null;
        }
    }

    @Override
    public Model resolve(Type type, ModelConverterContext context, Iterator<ModelConverter> chain) {
        if (chain.hasNext()) {
            return chain.next().resolve(type, context, chain);
        } else {
            return null;
        }
    }
}

您可以通过

注册自定义转换器
ModelConverters.getInstance().addConverter(new JsonNodeModelConverter());