当前位置: 首页 > 工具软件 > StringBean > 使用案例 >

controller返回string类型和bean的序列化、乱码

严兴旺
2023-12-01
/**
*  解决字符串返回乱码问题,指定UTF-8返回字符集
**/
@Bean
  public HttpMessageConverter<String> responseBodyConverter() {
    return new StringHttpMessageConverter(StandardCharsets.UTF_8);
  }

/**
*  解决DTO对象返回,反序列化问题
**/
  @Bean
  public ObjectMapper getObjectMapper() {
    ObjectMapper mapper = new  ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    return mapper;
  }

/**
*  配置Jackson
**/
  @Bean
  public MappingJackson2HttpMessageConverter messageConverter() {
    MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
    converter.setObjectMapper(getObjectMapper());
    return converter;
  }

  @Override
  public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    super.configureMessageConverters(converters);
    //解决中文乱码
    converters.add(responseBodyConverter());
    //返回JSON序列化问题
    converters.add(messageConverter());
  }
 类似资料: