springboot自定义json消息转换器

springboot自定义json消息转换器

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.TypeReference;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.util.StreamUtils;

import java.io.IOException;
import java.lang.reflect.Type;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
public class MyConverter extends MappingJackson2HttpMessageConverter {

    private static final String ITEM_CODE = "itemTypeCode";

	/**
	* read方法执行位置是请求参数到@requestBody之间,read方法返回的对象会赋值给@requestBody注释的对象
	*/
    @Override
    public Object read(Type type, Class<?> contextClass, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
        // 自定义读取请求消息的逻辑
        String requestBody = StreamUtils.copyToString(inputMessage.getBody(), Charset.defaultCharset());
		//验证是否包含要处理的关键字
        if (!requestBody.contains(ITEM_CODE) || StringUtils.isBlank(requestBody)) {
			//不符合处理规则就将json报文解析成对象
			//有坑:直接使用super.read()方法,父类使用jackson解析会报错
            return JSON.parseObject(requestBody,type);
        }
        MyOperationo peration = null;
        try {
        	//符合处理规则,将报文解析成指定类型
            operation = JSON.parseObject(requestBody, MyOperation.class);
        } catch (JSONException e) {
            return JSON.parseObject(requestBody,type);
        }

		//业务处理逻辑
		//operation handler

   
        return operation ;
    }

	@Override
	protected void writeInternal(Object object, @Nullable Type type, HttpOutputMessage outputMessage)
			throws IOException, HttpMessageNotWritableException {
		//writeInternal执行位置是在controller返回到@responseBody之间,将要返回给前端的报文写入outputMessage流中
		String json = JSON.toJSONString(object);
	    outputMessage.getBody().write(json.getBytes(StandardCharsets.UTF_8));
}

创建完自定义消息转换器后,还需要将消息转换器加到spring,默认的消息转换器列表中

import com.newland.boss.cloud.calculatefee.converter.OperationInConverter;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

/**
 * @author wk
 * @version V1.0
 * @date 2024/1/22 15:54
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
    	//需要将自定义消息转化器的处理优先级提高,否则会被其他处理器处理掉导致自定义处理器失效
        HttpMessageConverter<?> httpMessageConverter = converters.get(0);
        converters.add(0,new OperationInConverter());
        converters.add(httpMessageConverter);
    }
}

处理器优先级:
https://www.cnblogs.com/cainiao-Shun666/p/16016116.html