SpringMVC @RequestBody问题:Unrecognized field , not marked as ignorable

简介:

在使用Json传值并且使用@RequestBody注解的时候需要注意一些问题:

  1. 一个方法中只能有一个@RequestBody注解。
  2. 默认情况下@RequestBody标注的对象必须包含前台传来的所有字段。


第一条容易理解,因为RequestBody就是request的inputStream,这个流在第一次使用该注解后会关闭,后面的都会报错(stream closed)。


第二条如果没有包含前台传来的字段,就会报错:Unrecognized field xxx , not marked as ignorable,这是因为MappingJacksonHttpMessageConverter默认要求必须存在相应的字段。如果没有前台传来的某个字段,就会报错。。


解决方法有很多,可以增加一个字段来接收前台传来的这个值,如果存在多个字段,这种方式很不好(就算一个字段,如果没用,新增字段也不好)。


或者在前台往后台传值的时候,去掉无用的字段。这样还能减少网络传输的大小。


还有一些方法,这些方法主要是使用Jackson提供的json注解。


@JsonIgnore注解用来忽略某些字段,可以用在Field或者Getter方法上,用在Setter方法时,和Filed效果一样。这个注解只能用在POJO存在的字段要忽略的情况,不能满足现在需要的情况。


@JsonIgnoreProperties(ignoreUnknown = true),将这个注解写在类上之后,就会忽略类中不存在的字段,可以满足当前的需要。这个注解还可以指定要忽略的字段。使用方法如下:

@JsonIgnoreProperties({ "internalId", "secretKey" })

指定的字段不会被序列化和反序列化。

目录
相关文章
|
Serverless
attempt to delete a method
attempt to delete a method
227 1
shiro学习之错误 No realms have been configured! One or more realms must be present to execute an authori
shiro学习之错误 No realms have been configured! One or more realms must be present to execute an authori
|
6月前
|
JSON Java 数据格式
UnrecognizedPropertyException: Unrecognized field 解决
UnrecognizedPropertyException: Unrecognized field 解决
221 0
|
5月前
Unsatisfied dependency expressed through field 'restTemplate';
Unsatisfied dependency expressed through field 'restTemplate';
94 0
|
Java 数据库连接 Redis
Bean method ‘redisConnectionFactory‘ not loaded because @ConditionalOnClass did not find required c
Bean method ‘redisConnectionFactory‘ not loaded because @ConditionalOnClass did not find required c
134 0
|
8月前
Unsatisfied dependency expressed through field ‘baseMapper‘
Unsatisfied dependency expressed through field ‘baseMapper‘
54 2
|
Java 数据库连接 数据库
Unable to evaluate the expression Method threw ‘org.hibernate.LazyInitializationException‘ exceptio
Unable to evaluate the expression Method threw ‘org.hibernate.LazyInitializationException‘ exceptio
Error creating bean with name ‘userServiceImpl‘: Unsatisfied dependency expressed through field ‘bas
Error creating bean with name ‘userServiceImpl‘: Unsatisfied dependency expressed through field ‘bas
451 0
Unsatisfied dependency expressed through field ‘baseMapper‘; nested exception is org.springframewor
Unsatisfied dependency expressed through field ‘baseMapper‘; nested exception is org.springframewor
Unsatisfied dependency expressed through field ‘baseMapper‘; nested exception is org.springframewor
|
Web App开发 Java
conflicts with existing, non-compatible bean definition of same name and class
使用 Idea CE 创建的 Maven Web 项目,启动时却输出以下错误: Connected to the target VM, address: '127.0.0.1:52165', transport: 'socket'  .
2260 0