@JsonFormat和@JsonField注解无效解决

@JsonFormat是jackson包下的,@JsonField是阿里的fastjson包下的。两者都可以处理后台返回给前台的数据,常用来格式化后台的日期。

实现WebMvcConfigurer接口,重写configureMessageConverters方法,添加自定义消息转换器。

1.对于@JsonFormat注解无效:

    @Override
    public void configureMessageConverters(List> converters) {
        MappingJackson2HttpMessageConverter jackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
        ObjectMapper objectMapper = new ObjectMapper();
        // 解决long型JS精度丢失问题
        SimpleModule simpleModule = new SimpleModule();
        simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
        simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
        objectMapper.registerModule(simpleModule);
        jackson2HttpMessageConverter.setObjectMapper(objectMapper);
        converters.add(jackson2HttpMessageConverter);
    }

2.对于@JsonField注解无效:

	@Override
	public void configureMessageConverters(List> converters) {
		// 清除默认 Json 转换器
		converters.removeIf(converter -> converter instanceof MappingJackson2HttpMessageConverter);

		// 配置 FastJson
		FastJsonConfig config = new FastJsonConfig();
		config.setSerializerFeatures(SerializerFeature.QuoteFieldNames, 
                SerializerFeature.WriteEnumUsingToString,
				SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteDateUseDateFormat,
                SerializerFeature.BrowserCompatible,
				SerializerFeature.DisableCircularReferenceDetect);
		// 解决long型JS精度丢失问题
		SerializeConfig serializeConfig = SerializeConfig.globalInstance;
		serializeConfig.put(Long.class, ToStringSerializer.instance);
		serializeConfig.put(Long.TYPE, ToStringSerializer.instance);
		config.setSerializeConfig(serializeConfig);

		// 添加 FastJsonHttpMessageConverter
		FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new 
        FastJsonHttpMessageConverter();
		fastJsonHttpMessageConverter.setFastJsonConfig(config);
		List fastMediaTypes = new ArrayList<>();
		fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
		fastJsonHttpMessageConverter.setSupportedMediaTypes(fastMediaTypes);
		converters.add(fastJsonHttpMessageConverter);
	}

你可能感兴趣的:(java)