springMVC 、springboot中返回前端JSON 时候,经常需要不同的格式 实现方式有几种
一 、自己实现JSON序列化器
序列化对象上使用
public class TopSymbolVo implements Serializable {
@JsonSerialize(using = BigDecimalSerializer.class)
private BigDecimal price;
}
JSON 序列化器实现
public class BigDecimalSerializer extends JsonSerializer<BigDecimal> {
@Override
public void serialize(BigDecimal value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
jgen.writeString(value.stripTrailingZeros().toPlainString());
}
}
二、 自定义注释
定义注释
@Target({ElementType.METHOD,ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface DateFormatter { String pattern() default "yyyy-MM-dd HH:mm:ss"; }
//定义序列化器
import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; import org.apache.commons.lang3.StringUtils; import java.io.IOException; import java.util.Date; public class DateSerializer extends JsonSerializer<Date> { private final String pattern; public DateSerializer(String pattern) { super() this.pattern = pattern; } @Override public void serialize(Date date, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException { String output = StringUtils.EMPTY; if (date != null) { output = new SimpleDateFormat(pattern).format(date); } jsonGenerator.writeString(output); } }
// JacksonAnnotationIntrospector
import com.fasterxml.jackson.databind.introspect.Annotated; import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector; public class DateFormatterAnnotationIntrospector extends JacksonAnnotationIntrospector { @Override public Object findSerializer(Annotated annotated) { DateFormatter formatter = annotated.getAnnotation(DateFormatter.class); if (formatter != null) { return new DateSerializer(formatter.pattern()); } return super.findSerializer(annotated); } }
//加入配置 或者在上一步中@bean 自动扫描加入 @Configuration public class WebServerConfig { @Bean public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() { // Config the Json convert Chinese garbled. // 这里的配置可能会导致application.properties文件中spring.jackson.time-zone=GMT+8失效 MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); // 不设置Utf-8格式,可能会导致Mock测试输出信息乱码 converter.setDefaultCharset(StandardCharsets.UTF_8); ObjectMapper objectMapper = converter.getObjectMapper(); objectMapper.setTimeZone(TimeZone.getDefault()); objectMapper.setAnnotationIntrospector(new DateFormatterAnnotationIntrospector()); return converter; } }