tech.mhuang.pacebox.springboot.autoconfiguration.jackson.JacksonConfigurer Maven / Gradle / Ivy
The newest version!
package tech.mhuang.pacebox.springboot.autoconfiguration.jackson;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import tech.mhuang.pacebox.core.io.IOUtil;
import tech.mhuang.pacebox.core.util.ObjectUtil;
import java.io.IOException;
import java.lang.reflect.Type;
import java.nio.charset.Charset;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* jacksonConfig解决String双引号问题
*
* @author mhuang
* @since 1.0.0
*/
public class JacksonConfigurer implements WebMvcConfigurer {
public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
return new MappingJackson2HttpMessageConverter() {
@Override
protected void writeInternal(Object object, Type type, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
if (object instanceof String str) {
Charset charset = this.getDefaultCharset();
if (ObjectUtil.isEmpty(charset)) {
charset = Charset.defaultCharset();
}
IOUtil.write(str, outputMessage.getBody(), charset);
} else {
super.writeInternal(object, type, outputMessage);
}
}
};
}
@Override
public void configureMessageConverters(List> converters) {
MappingJackson2HttpMessageConverter converter = mappingJackson2HttpMessageConverter();
converter.setSupportedMediaTypes(Stream.of(MediaType.TEXT_HTML, MediaType.APPLICATION_JSON).collect(Collectors.toList()));
converters.add(new StringHttpMessageConverter());
converters.add(converter);
}
}