NutzCN Logo
问答 泛型 List 反序列化异常 json转换 TypeReference HttpMessageConversionException
发布于 577天前 作者 Hamming 1052 次浏览 复制 上一个帖子 下一个帖子
标签:

请求里面 用到 token 身份验证 还有data 于是打算写成泛型

package com.icss.bean;

import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.AllArgsConstructor;
import lombok.Getter;

import java.sql.Timestamp;
import java.util.List;

/**
 * 接口传参 公用类
 * @author Haiming
 * @date 2020/10/21 9:16 AM
 */
@Getter
@AllArgsConstructor
public class RequestArrayData<T> {

    private String token;

    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Timestamp requestDate;

    private List<T> data;
    
}

定义如下类 接收参数

package com.icss.bean;

import lombok.Getter;

import java.sql.Timestamp;
import java.util.List;

/**
 * @author Haiming
 * @date 2020/10/21 3:27 PM
 */
@Getter
public class VisualInventoryData  extends RequestArrayData<VisualInventoryData>{

    private String whCode;

    private String position;

    private String brandCode;

    private String brandName;

    private Long num1;

    private Long lockNum;

    private Double positionLockInRatio;

    public VisualInventoryData(String token, Timestamp requestDate, List<VisualInventoryData> data) {
        super(token, requestDate, data);
    }

}

传json 转实体类的时候 异常了

org.springframework.http.converter.HttpMessageConversionException: Type definition error: [simple type, class com.icss.bean.VisualInventoryData]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `com.icss.bean.VisualInventoryData` (no Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator)
 at [Source: (PushbackInputStream); line: 2, column: 5]
	at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:242)
	at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.read(AbstractJackson2HttpMessageConverter.java:227)
	at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodArgumentResolver.readWithMessageConverters(AbstractMessageConverterMethodArgumentResolver.java:204)
	at org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.readWithMessageConverters(RequestResponseBodyMethodProcessor.java:157)
	at org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.resolveArgument(RequestResponseBodyMethodProcessor.java:130)
	at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:124)
	at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:165)
	at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
	at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
	at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)
	at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:800)
	at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
	at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1038)
	at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942)
	at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:998)
	at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:901)

spring参数接收如下

    @PostMapping(value = "/industrialWmsElevatedLibrary")
    @Log("工业WMS 高架库 数据同步")
    @ApiOperation("工业WMS 高架库 数据同步")
    public Result industrialWmsElevatedLibrary( @RequestBody VisualInventoryData resources){
        VisualInventoryService.insertOrUpdate(resources,VisualInventoryDataType.INDUSTRIAL_WMS_ELEVATED_LIBRARY);
        return Result.success("请求成功");
    }

查了很多文档 貌似需要 TypeReference 那么 我要怎么处理呢 求大佬指定

7 回复

查了很多资料 https://github.com/alibaba/fastjson/issues/2361
这个上面 也没给解决方法

传参json

{
    "token":"BBCF+WMSSYSTEM+PUSHMACHANICALFAULT",
    "data":[
        {
            "whCode":"W12530401463",
            "brandCode":"6901028194419",
            "position":"货位1",
            "num1":"20000",
            "positionLockInRatio":"0.80"
        },
        {
            "whCode":"W12530401463",
            "brandCode":"6901028194418",
            "position":"货位2",
            "num1":"20000",
            "positionLockInRatio":"0.80"
        },
        {
            "whCode":"W12530401463",
            "brandCode":"6901028194417",
            "position":"货位3",
            "num1":"20000",
            "positionLockInRatio":"0.70"
        }
    ]
}

springboot 里面配置json 处理 可以解决

@Configuration
@EnableWebMvc
public class Application extends WebMvcConfigurerAdapter {

    @Override
    public void configureMessageConverters(List<HttpMessageConverter < ? >> converters) {
        GsonHttpMessageConverter gsonHttpMessageConverter = new GsonHttpMessageConverter();
        converters.add(gsonHttpMessageConverter);
    }
}

最终使用

    /**
     * 使用阿里 FastJson 作为JSON MessageConverter
     * @param converters
     */
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();

//        log.info("converters:" + converters.toString());
        List<MediaType> supportMediaTypeList = new ArrayList<>();
//        supportMediaTypeList.add(MediaType.TEXT_HTML);
        supportMediaTypeList.add(MediaType.APPLICATION_JSON_UTF8);
//        supportMediaTypeList.add(MediaType.IMAGE_GIF);
//        supportMediaTypeList.add(MediaType.IMAGE_JPEG);
//        supportMediaTypeList.add(MediaType.IMAGE_PNG);

        FastJsonConfig config = new FastJsonConfig();
        config.setDateFormat("yyyy-MM-dd HH:mm:ss");
        config.setSerializerFeatures(
                //保留空的字段
                SerializerFeature.WriteMapNullValue,
                //String null -> ""
                SerializerFeature.WriteNullStringAsEmpty,
                //Number null -> 0
                SerializerFeature.WriteNullNumberAsZero,
                //List null-> []
                SerializerFeature.WriteNullListAsEmpty,
                //Boolean null -> false
                SerializerFeature.WriteNullBooleanAsFalse);
        converter.setFastJsonConfig(config);
        converter.setSupportedMediaTypes(supportMediaTypeList);
        converter.setDefaultCharset(Charset.forName("UTF-8"));
        converters.add(converter);
    }

json 关联 解析会出问题 需要加上 SerializerFeature.DisableCircularReferenceDetect,

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();

//        log.info("converters:" + converters.toString());
        List<MediaType> supportMediaTypeList = new ArrayList<>();
//        supportMediaTypeList.add(MediaType.TEXT_HTML);
        supportMediaTypeList.add(MediaType.APPLICATION_JSON_UTF8);
//        supportMediaTypeList.add(MediaType.IMAGE_GIF);
//        supportMediaTypeList.add(MediaType.IMAGE_JPEG);
//        supportMediaTypeList.add(MediaType.IMAGE_PNG);

        FastJsonConfig config = new FastJsonConfig();
        config.setDateFormat("yyyy-MM-dd HH:mm:ss");
        config.setSerializerFeatures(
                SerializerFeature.DisableCircularReferenceDetect,
                //保留空的字段
                SerializerFeature.WriteMapNullValue,
                //String null -> ""
                SerializerFeature.WriteNullStringAsEmpty,
                //Number null -> 0
                SerializerFeature.WriteNullNumberAsZero,
                //List null-> []
                SerializerFeature.WriteNullListAsEmpty,
                //Boolean null -> false
                SerializerFeature.WriteNullBooleanAsFalse);
        converter.setFastJsonConfig(config);
        converter.setSupportedMediaTypes(supportMediaTypeList);
        converter.setDefaultCharset(Charset.forName("UTF-8"));
        converters.add(converter);
    }

腾讯云双11.11 云上盛惠
1核2G1M,88元/1年
2核4G3M,698元/3年
4核8G5M,1501元/1年,3962元/3年
8核16G5M,2813元/1年
更多进入活动地址:
https://curl.qcloud.com/fk3zBX1F

【阿里云】双11拼团活动组队中
1核2G1M,85元/1年,254/3年
2核4G3M,295元/1年,664元/3年
4核8G5M,1000元/1年,3000元/3年
更多进入活动地址:
https://c.tb.cn/k6.GzhOc?userCode=wbqjs7bw

添加回复
请先登陆
回到顶部