Springboot 项目JSON parse error: Unrecognized field "xxx"错误

开发中遇到前端请求后端保存接口的时候 出现JSON parse error: Unrecognized field "xxx"的错误。经查,前端组装的对象中有多余的字段,后端转实体类的时候无法识别到该字段。
在使用Json传值并且使用@RequestBody注解的时候,默认情况下@RequestBody标注的对象必须包含前台传来的所有字段。


解决方案常用的有如下两种。

1.在实体类加注解 @JsonIgnoreProperties(ignoreUnknown = true) ,如下

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

import java.io.Serializable;
import java.sql.Date;

/**
 * @version v 1.0.
 * @Descrption 质量检测VO
* @Author wangzhy
 * @Date 2019-11-01
 */
@JsonIgnoreProperties(ignoreUnknown = true)
public class DseZljcVo implements Serializable {

    private static final long serialVersionUID = 6135511086872247687L;
    /**
     * 主建
     */
    private String zljcid;

    /**
     * 项目代码
     */
    private String xmdm;
}

以上的 要为每个实体类都加上注解,工作量比较大。

2.通过配置文件全局配置。配置文件代码如下

package com.dse.config;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @version v 1.0.
 * @Descrption
 * @Copyright: Copyright 2019 ShenZhen DSE Corporation
 * @Company 深圳市东深电子科技股份有限公司
 * @Author wangzhy
 * @Date 2019-11-23
 */
@Configuration
public class MvcConfig implements WebMvcConfigurer {


    @Bean
    public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter(){

        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        ObjectMapper objectMapper = new ObjectMapper();
        //添加此配置
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        converter.setObjectMapper(objectMapper);
        return converter;
    }


}

我在项目中使用的第二种方式,配置好后就不会报Unrecognized field "xxx"错误了。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。