@ApiModelProperty的name属性无效解决方案
2020-01-15 本文已影响0人
码农梦醒
@ApiModelProperty的name属性作用是修改参数的属性名,但实际使用的时候,发现是无效的,此时要怎么办?
解决方案:
- 如果你springboot项目json转换使用的是jackson, 那么只需要使用
@JsonProperty
修改成你需要的属性名 - 如果你springboot项目json转换使用的是fastjson,那么首先需要使用
@JSONField
修改成你需要的属性名, 然后对fastjson进行配置
@Configuration
@EnableSwagger2
public class Swagger2 {
@Autowired
private ApplicationContext applicationContext;
@PostConstruct
public void setObjectMapper() {
ObjectMapper objectMapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
objectMapper.registerModule(module);
objectMapper.setAnnotationIntrospector(new JacksonAnnotationIntrospector() {
@Override
public boolean isAnnotationBundle(Annotation ann) {
if (ann.annotationType() == JSONField.class) {
return true;
}
return super.isAnnotationBundle(ann);
}
@Override
public PropertyName findNameForSerialization(Annotated a) {
PropertyName nameForSerialization = super.findNameForSerialization(a);
if (nameForSerialization == null || nameForSerialization == PropertyName.USE_DEFAULT) {
JSONField jsonField = _findAnnotation(a, JSONField.class);
if (jsonField != null) {
return PropertyName.construct(jsonField.name());
}
}
return nameForSerialization;
}
@Override
public PropertyName findNameForDeserialization(Annotated a) {
PropertyName nameForDeserialization = super.findNameForDeserialization(a);
if (nameForDeserialization == null || nameForDeserialization == PropertyName.USE_DEFAULT) {
JSONField jsonField = _findAnnotation(a, JSONField.class);
if (jsonField != null) {
return PropertyName.construct(jsonField.name());
}
}
return nameForDeserialization;
}
});
ObjectMapperConfigured objectMapperConfigured = new ObjectMapperConfigured(applicationContext, objectMapper);
applicationContext.publishEvent(objectMapperConfigured);
}
}
参考
Why does @ApiModelProperty “name” attribute has no effect?