前言
项目中使用了FastJson,并定义了实体字段展示的名称,比如就像下面这样
@Data
public class User {
@JSONField(name = "UserId")
@ApiModelProperty("用户ID")
private Integer id;
@JSONField(name = "Name")
@ApiModelProperty("姓名")
private String name;
@JSONField(name = "Age")
@ApiModelProperty("年龄")
private Integer age;
@JSONField(name = "Sex")
@ApiModelProperty("性别")
private String sex;
@JSONField(name = "Address")
@ApiModelProperty("地址")
private String address;
@JSONField(name = "Email")
@ApiModelProperty("邮箱")
private String email;
}
一、默认情况下的展示效果
二、看一下改过后的效果
三、如何操作
自己定义一个ApiModelPropertyPropertyBuilder代码如下
package com.zhoule.demo.config;
import com.alibaba.fastjson.annotation.JSONField;
import io.swagger.annotations.ApiModelProperty;
import org.springframework.stereotype.Component;
import springfox.documentation.builders.PropertySpecificationBuilder;
import springfox.documentation.schema.property.ModelSpecificationFactory;
import springfox.documentation.spi.schema.contexts.ModelPropertyContext;
import springfox.documentation.spring.web.DescriptionResolver;
import springfox.documentation.swagger.schema.ApiModelPropertyPropertyBuilder;
import java.lang.reflect.Field;
import java.util.Optional;
import static java.util.Optional.empty;
import static springfox.documentation.schema.Annotations.findPropertyAnnotation;
@Component
public class ApiModelPropertyPropertyBuilderFromFastJson extends ApiModelPropertyPropertyBuilder {
public ApiModelPropertyPropertyBuilderFromFastJson(DescriptionResolver descriptions, ModelSpecificationFactory modelSpecifications) {
super(descriptions, modelSpecifications);
}
@Override
public void apply(ModelPropertyContext context) {
super.apply(context);
Optional<ApiModelProperty> apiModelProperty = empty();
Optional<JSONField> jsonField = empty();
if (context.getBeanPropertyDefinition().isPresent()) {
apiModelProperty = apiModelProperty.map(Optional::of).orElse(findPropertyAnnotation(
context.getBeanPropertyDefinition().get(),
ApiModelProperty.class));
jsonField = jsonField.map(Optional::of).orElse(findPropertyAnnotation(
context.getBeanPropertyDefinition().get(),
JSONField.class));
}
Optional<ApiModelProperty> finalApi = apiModelProperty;
Optional<JSONField> finalJson = jsonField;
if (finalApi.isPresent() && finalJson.isPresent()) {
//通过反射修改字段值
PropertySpecificationBuilder specificationBuilder = context.getSpecificationBuilder();
try {
Field field = specificationBuilder.getClass().getDeclaredField("name");
field.setAccessible(true);
Object oldValue = field.get(specificationBuilder);
if (oldValue == null) {
oldValue = "";
}
field.set(specificationBuilder, finalJson.map(JSONField::name).orElse(oldValue.toString()));
} catch (NoSuchFieldException | IllegalAccessException e) {
e.printStackTrace();
}
}
}
}