首页 > 解决方案 > 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:我在同一个项目中的另外两个类(类别和产品)之间有相同的关系,而且效果很好,女巫很奇怪。

标签: javajsonhibernatespring-boot

解决方案


推荐阅读