当前位置:   article > 正文

Swagger使用Map接受参数时,页面如何显示具体参数及说

Swagger使用Map接受参数时,页面如何显示具体参数及说

Swagger使用Map接受参数时,页面如何显示具体参数及说明

1.需求说明

项目为:SpringBoot+Knife+MyBatisPlus

后端使用Map接受参数,要求在swagger页面上显示具体的参数名称、类型及说明

2.解决方案

1.参数数量少

当Map接受参数数量少时,可以使用Swagger自带的注解 @ApiImplicitParams+@ApiImplicitParam,具体如下:

  1. @GetMapping("/list")
  2. @ApiImplicitParams({
  3. @ApiImplicitParam(name = "code", value = "字典编号", paramType = "query", dataType = "string"),
  4. @ApiImplicitParam(name = "dictValue", value = "字典名称", paramType = "query", dataType = "string")
  5. })
  6. @ApiOperationSupport(order = 2)
  7. @ApiOperation(value = "列表", notes = "传入dict")
  8. public R list(@ApiIgnore @RequestParam Map<String, Object> dict) {
  9. }

2.参数数量大且有具体的实体类或DTO

  1. 自定义注解 @ApiGlobalModel

    1. package com.zjjg.dlbp.config.annotation;
    2. /**
    3. * @author 石智铭
    4. * @Date 2022-10-10
    5. */
    6. import java.lang.annotation.ElementType;
    7. import java.lang.annotation.Retention;
    8. import java.lang.annotation.RetentionPolicy;
    9. import java.lang.annotation.Target;
    10. /**
    11. * Swagger扩展注解
    12. * 用于 application/json请求
    13. * 并使用诸如Map或JSONObject等非具体实体类接收参数时,对参数进行进一步描述
    14. */
    15. @Target({
    16. ElementType.METHOD, ElementType.PARAMETER})
    17. @Retention(RetentionPolicy.RUNTIME)
    18. public @interface ApiGlobalModel {
    19. /**
    20. * 字段集合容器
    21. *
    22. * @return Global model
    23. */
    24. Class<?> component();
    25. /**
    26. * 分隔符
    27. *
    28. * @return separator
    29. */
    30. String separator() default ",";
    31. /**
    32. * 实际用到的字段
    33. * 可以是字符串数组,也可以是一个字符串 多个字段以分隔符隔开: "id,name"
    34. * 注意这里对应的是component里的属性名,但swagger显示的字段名实际是属性注解上的name
    35. *
    36. * @return value
    37. */
    38. String[] value() default {
    39. };
    40. }
    1. 编写处理注解对应的插件

      1. package com.zjjg.dlbp.config;
      2. import cn.hutool.core.util.IdUtil;
      3. import com.fasterxml.classmate.TypeResolver;
      4. import com.zjjg.dlbp.config.annotation.ApiGlobalModel;
      5. import io.swagger.annotations.ApiModelProperty;
      6. import javassist.*;
      7. import javassist.bytecode.AnnotationsAttribute;
      8. import javassist.bytecode.ConstPool;
      9. import javassist.bytecode.annotation.Annotation;
      10. import javassist.bytecode.annotation.StringMemberValue;
      11. import lombok.AllArgsConstructor;
      12. import org.apache.commons.lang3.StringUtils;
      13. import org.slf4j.Logger;
      14. import org.slf4j.LoggerFactory;
      15. import org.springblade.core.tool.utils.Func;
      16. import org.springframework.core.annotation.Order;
      17. import org.springframework.stereotype.Component;
      18. import springfox.documentation.schema.ModelRef;
      19. import springfox.documentation.spi.DocumentationType;
      20. import springfox.documentation.spi.service.ParameterBuilderPlugin;
      21. import springfox.documentation.spi.service.contexts.ParameterContext;
      22. import java.util.*;
      23. import java.util.stream.Collectors;
      24. /**
      25. * @author 石智铭
      26. * @Date 2022-10-10
      27. * 将map入参匹配到swagger文档中
      28. * plugin加载顺序,默认是最后加载
      29. */
      30. @Component
      31. @Order
      32. @AllArgsConstructor
      33. public class ApiGlobalModelBuilder implements ParameterBuilderPlugin {
      34. private static final Logger logger = LoggerFactory.getLogger(ApiGlobalModelBuilder.class);
      35. private final TypeResolver typeResolver;
      36. @Override
      37. public void apply(ParameterContext context) {
      38. try {
      39. // 从方法或参数上获取指定注解的Optional
      40. Optional<ApiGlobalModel> optional = context.getOperationContext().findAnnotation(ApiGlobalModel.class);
      41. if (!optional.isPresent()) {
      42. optional = context.resolvedMethodParameter().findAnnotation(ApiGlobalModel.class);
      43. }
      44. if (optional.isPresent()) {
      45. Class originClass = context.resolvedMethodParameter().getParameterType().getErasedType();
      46. String name = originClass.getSimpleName() + "Model" + IdUtil.objectId();
      47. ApiGlobalModel apiAnnotation = optional.get();
      48. String[] fields = apiAnnotation.value();
      49. String separator = apiAnnotation.separator();
      50. ClassPool pool = ClassPool.getDefault();
      51. CtClass ctClass = pool.makeClass(name);
      52. ctClass.setModifiers(Modifier.PUBLIC);
      53. //处理 javassist.NotFoundException
      54. pool.insertClassPath(new ClassClassPath(apiAnnotation.component()));
      55. CtClass globalCtClass = pool.getCtClass(apiAnnotation.component().getName());
      56. // 将生成的Class添加到SwaggerModels
      57. context.getDocumentationContext()
      58. .getAdditionalModels()
      59. .add(typeResolver.resolve(createRefModel(fields,separator,globalCtClass,ctClass)));
      60. // 修改Json参数的ModelRef为动态生成的class
      61. context.parameterBuilder()
      62. .parameterType("body")
      63. .modelRef(new ModelRef(name)).name(name).description("body");
      64. }
      65. } catch (Exception e) {
      66. logger.error("@ApiGlobalModel Error",e);
      67. }
      68. }
      69. @Override
      70. public boolean supports(DocumentationType delimiter) {
      71. return true;
      72. }
      73. /**
      74. * 根据fields中的值动态生成含有Swagger注解的javaBeen modelClass
      75. */
      76. private Class createRefModel(String[] fieldValues,String separator,CtClass origin,CtClass modelClass) throws NotFoundException, CannotCompileException, ClassNotFoundException {
      77. List<CtField> allField=getAllFields(origin);
      78. List<CtField> modelField;
      79. if (Func.isEmpty(fieldValues)){
      80. modelField = allField;
      81. }else {
      82. List<String> mergeField = merge(fieldValues, separator);
      83. modelField = allField.stream().filter(e->mergeField.contains(e.getName())).collect(Collectors.toList());
      84. }
      85. createCtFields(modelField, modelClass);
      86. return modelClass.toClass();
      87. }
      88. public void createCtFields(List<CtField> modelField, CtClass ctClass) throws CannotCompileException, ClassNotFoundException, NotFoundException {
      89. for (CtField ctField : modelField) {
      90. CtField field = new CtField(ClassPool.getDefault().get(ctField.getType().getName()), ctField.getName(), ctClass);
      91. field.setModifiers(Modifier.PUBLIC);
      92. ApiModelProperty annotation = (ApiModelProperty) ctField.getAnnotation(ApiModelProperty.class);
      93. String apiModelPropertyValue = java.util.Optional.ofNullable(annotation).map(s -> s.value()).orElse("");
      94. //添加model属性说明
      95. if (StringUtils.isNotBlank(apiModelPropertyValue)) {
      96. ConstPool constPool = ctClass.getClassFile().getConstPool();
      97. AnnotationsAttribute attr = new AnnotationsAttribute(constPool, AnnotationsAttribute.visibleTag);
      98. Annotation ann = new Annotation(ApiModelProperty.class.getName(), constPool);
      99. ann.addMemberValue("value", new StringMemberValue(apiModelPropertyValue, constPool));
      100. attr.addAnnotation(ann);
      101. field.getFieldInfo().addAttribute(attr);
      102. }
      103. ctClass.addField(field);
      104. }
      105. }
      106. /**
      107. * 获取本类及其父类的字段属性 字段属性去重
      108. * @param clazz 当前类对象
      109. * @return 字段数组
      110. */
      111. public List<CtField> getAllFields(CtClass clazz) throws NotFoundException {
      112. List<CtField> fieldList = new ArrayList<>();
      113. while (clazz != null){
      114. fieldList.addAll(new ArrayList<>(Arrays.asList(clazz.getDeclaredFields())));
      115. clazz = clazz.getSuperclass();
      116. }
      117. return fieldList.stream().collect(Collectors.collectingAndThen(
      118. Collectors.toCollection(() -> new TreeSet<CtField>(Comparator.comparing(CtField::getName))), ArrayList::new)
      119. );
      120. }
      121. /**
      122. * 字符串列表 分隔符 合并
      123. * A{"a","b,c","d"} => B{"a","d","b","c"}
      124. *
      125. * @param arr arr
      126. * @return list
      127. */
      128. private List<String> merge(String[] arr, String separator) {
      129. List<String> tmp = new ArrayList<>();
      130. Arrays.stream(arr).forEach(s -> {
      131. if (s.contains(separator)) {
      132. tmp.addAll(Arrays.asList(s.split(separator)));
      133. } else {
      134. tmp.add(s);
      135. }
      136. });
      137. return tmp;
      138. }
      139. }
      1. 在具体Controller上添加注解
      1. /**
      2. * 修改
      3. */
      4. @PostMapping("/update")
      5. @ApiOperationSupport(order = 2)
      6. @ApiOperation(value = "修改结构物:DLBP-0002-002", notes = "修改结构物:DLBP-0002-002")
      7. @ApiGlobalModel(component = SlopeDTO.class)
      8. public R update(@RequestBody Map<String,Object> slopeDTO) {
      9. return R.status(slopeService.updateSlope(slopeDTO));
      10. }
      1. 存在问题
        1. 无法展示实体类中对象属性或对象集合
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/890242
推荐阅读