严重: Servlet.service() for servlet [dispatcher] in
context with path [] threw exception [Request
processing failed; nested exception is org.springframework.http.converter.HttpMessageConversionException:
Type definition error: [simple type, class com.djh.entity.UserEntity];
nested exception is com.fasterxml.jackson.databind.exc.
InvalidDefinitionException: Cannot construct instance
of `com.djh.entity.UserEntity` (no Creators,
like default construct, exist): cannot deserialize
from Object value (no delegate- or property-based Creator) at [Source: (PushbackInputStream); line: 2,
column: 5]] with root cause com.fasterxml.
jackson.databind.exc.InvalidDefinitionException:
Cannot construct instance of `com.djh.entity.UserEntity`
(no Creators, like default construct, exist):
cannot deserialize from Object value
(no delegate- or property-based Creator)
今天,我在用POSTMAN 来模拟网页请求的时候发生了以上问题,我是利用实体类来接受json数据,以下是纠错前的实体类。
package com.djh.entity;
import org.omg.PortableInterceptor.INACTIVE;
public class UserEntity {
private String name;
private Integer age;
public UserEntity(String name, Integer age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "UserEntity{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
这是控制类
package com.djh.controller;
import com.djh.entity.UserEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller()
@RequestMapping("/add")
public class AddController {
/**
* 加上@Controller注解 标记为springmvc控制类
*/
@RequestMapping(value = "/demo01",method = RequestMethod.POST)
@ResponseBody
public String demo01(@RequestBody UserEntity userEntity) {
return userEntity.toString();
}
}
就发送这个json数据,用UserEntity来接收,结果就报了最上面的错误。
看了一下,有的说是mapping映射没对齐,我就两个参数,是对齐的,仔细研究了一下报错的代码,发现:
嵌套异常为com.fasterxml.jackson.databind.exc.InvalidDefinitionException:
无法构造“com.djh.entity”的实例。UserEntity`(不存在创建者,如默认构造):不能
从对象值反序列化(没有基于委托或属性的创建者)
这个意思就是entity实体类没有构造方法,但是我记得我生成过构造方法的。
public UserEntity(String name, Integer age) {
this.name = name;
this.age = age;
}
只能把无参构造函数也加进去。然后就成功了。
这个例子侧面说明了这个用实体类接受json的方法底层是spring控制反转用无参构造方法,然后再用setter来设置参数的。