java - JSON解析错误:无法构造实体类的实例
问题描述
我创建了这样的 OneToMany 关系:
@Entity
//@JsonDeserialize(as = User.class)
public class Role implements Serializable {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name = "id", updatable = false, nullable = false)
private Long id;
@Column(name = "roleName", unique = true, nullable = false)
private String roleName;
@OneToMany(cascade = {CascadeType.ALL}, mappedBy = "role", fetch = FetchType.LAZY)
@JsonManagedReference
private Set<User> users = new HashSet<User>();
}
@Entity
public class User implements Serializable {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name = "id", updatable = false, nullable = false)
private Long id;
@Column(name = "username", unique = true, nullable = false)
private String username;
@Column(name = "email", unique = true, nullable = false)
private String email;
@Column(name = "password", nullable = false)
private String password;
@Column(name = "firstName", nullable = false)
private String firstName;
@Column(name = "lastName", nullable = false)
private String lastName;
@ManyToOne
@JoinColumn(name = "fk_role")
@JsonBackReference
private Role role;
}
当我尝试使用 post 方法以 JSON 格式添加新用户时:
{
"username": "XXXX",
"email": "XXXX@gmail.com",
"password": "XXXX",
"firstName": "XXXX",
"lastName": "XXXX",
"role": 1
}
我收到此错误:
{
"timestamp": "2018-05-09T19:35:55.057+0000",
"status": 400,
"error": "Bad Request",
"message": "JSON parse error: Cannot construct instance of `org.vi.entities.Role` (although at least one Creator exists): no int/Int-argument constructor/factory method to deserialize from Number value (1); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `org.vi.entities.Role` (although at least one Creator exists): no int/Int-argument constructor/factory method to deserialize from Number value (1) at [Source: (PushbackInputStream); line: 7, column: 9] (through reference chain: org.vi.entities.User["role"])",
"path": "/users"
}
我已经尝试添加@JsonDeserialize(as = User.class)
到角色类,但它给了我另一个错误,Content type 'application/json;charset=UTF-8' not supported
即使 Content-Type 已经存在于标题中。
请问你能帮我解决这个问题吗?
PS:我在同一个项目中的另外两个类(类别和产品)之间有相同的关系,而且效果很好,女巫很奇怪。
解决方案
推荐阅读
- macos - macOS L2CAP 蓝牙插座
- java - Spring JPA:导致预期加入的路径
- r - 只有当另一个公共变量的值相等时,是否有一个 R 函数可以用另一个数据帧中的值替换一个数据帧中的值?
- eos - 如何确定是否需要创建钱包?
- r - Calculating probability using simulation
- vega - 有没有办法在 vega 重复图中的 vega 表达式中使用图号/标识符?
- java - 如何在 Java8 中按流对 Map 对象按时间段求和?
- c# - 内部错误 500 Azure 门户出现错误,但在本地运行正常
- postgresql - PostgreSQL 从值更新将空值视为文本
- r - 如何使for循环忽略几列并在excel文件中执行rbind所有工作表(不管工作表的总量)