有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java JSON解析错误:无法构造实体类的实例

我创造了一段这样的单身关系:

@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,即使标题中已经存在内容类型

你能帮我吗

PS:我在同一个项目中的另外两个类(类别和产品)之间有相同的关系,它工作得非常完美,这很奇怪


共 (0) 个答案