如果项目要求更改原生字段的展示形式。如date boolean等类型。虽然可以口头约定,但是这个不是最好的办法。个人觉得最好的办法就是不改。如果要改的话,只能在swagger2的序列化程序上入手。没办法,这方面springfox swagger2在现在的版本是写死的。我用的版本是2.9.2。
首先要写一个springfox swagger的序列化器的覆盖
import java.util.Collections;
import java.util.List;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import springfox.documentation.spring.web.json.JacksonModuleRegistrar;
import springfox.documentation.spring.web.json.Json;
import springfox.documentation.spring.web.json.JsonSerializer;
/**
* 覆盖swagger的实现以使用自己定义的序列化规则
* @author yanggan
* @date 2019年1月25日 下午6:33:42
*/
public class JsonSerializerOverride extends JsonSerializer {
public JsonSerializerOverride(List<JacksonModuleRegistrar> modules, ObjectMapper objectMapper) {
super(Collections.emptyList());
this.objectMapper = objectMapper;
for (JacksonModuleRegistrar each : modules) {
each.maybeRegisterModule(objectMapper);
}
}
private ObjectMapper objectMapper;
@Override
public Json toJson(Object toSerialize) {
try {
return new Json(objectMapper.writeValueAsString(toSerialize));
} catch (JsonProcessingException e) {
throw new RuntimeException("Could not write JSON", e);
}
}
}
然后编写自定义序列化
import java.io.IOException;
import java.util.Arrays;
import org.springframework.beans.BeanUtils;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import io.swagger.models.properties.BooleanProperty;
import io.swagger.models.properties.IntegerProperty;
public class BooleanPropertySerializer extends JsonSerializer<BooleanProperty> {
private ObjectMapper objectMapper = new ObjectMapper();
public BooleanPropertySerializer(ObjectMapper objectMapper) {
super();
this.objectMapper = objectMapper;
}
@Override
public void serialize(BooleanProperty value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
IntegerProperty newBooleanProperty = new IntegerProperty();
BeanUtils.copyProperties(value, newBooleanProperty);
newBooleanProperty.setType("integer");
newBooleanProperty.setFormat("int32");
newBooleanProperty.setExample(1);
newBooleanProperty.setEnum(Arrays.asList(0, 1));
JsonNode valueToTree = objectMapper.valueToTree(newBooleanProperty);
gen.writeTree(valueToTree);
}
@Override
public Class<BooleanProperty> handledType() {
return BooleanProperty.class;
}
}
最后在配置里覆盖JsonSerializer
@Bean
@Primary
public JsonSerializer jsonSerializer(List<JacksonModuleRegistrar> modules) {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setSerializationInclusion(Include.NON_NULL);
Jackson2ObjectMapperBuilder build = Jackson2ObjectMapperBuilder.json()
.serializers( new BooleanPropertySerializer(objectMapper));
return new JsonSerializerOverride(modules, build.build());
}
这样就行了