我是spring新手,我正在尝试测试restapi接口。其中一个端点是“/users”,该端点的get请求响应(与postman一起发送)如下所示:
{
"_embedded": {
"users": [
{
"user_id": 77,
"username": "test",
"password": "$2a$10$NlCTyjTbetNxOvJAMgOzB.ILztgwp1PjG9KoMjIA4I8Oc6Uc9iEGO",
"enabled": true,
"money": 0,
"strategies": [],
"roles": [
{
"name": "ROLE_ADMIN",
"privileges": [
{
"name": "FIRST_PRIVILEGE"
},
{
"name": "SECOND_PRIVILEGE"
}
]
}
],
"_links": {
"self": {
"href": "http://localhost:8080/users/test"
},
"users": {
"href": "http://localhost:8080/users"
},
"strategies": {
"href": "http://localhost:8080/users/{id}/strategies",
"templated": true
}
}
}
]
},
"_links": {
"self": {
"href": "http://localhost:8080/users"
}
}
}
用户类如下:
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long user_id;
@Size(min=4, max=12, message="required")
private String username;
private String password;
private boolean enabled;
private int money;
//Json Ignore so we dont have a neverending recursion
@JsonIgnoreProperties("users")
@ManyToMany(cascade= CascadeType.PERSIST)
private List<Strategy> strategies = new ArrayList<Strategy>();
+getters and setters
在我的代码中,我编写了一个函数,该函数应该向该端点发送get请求,并获取一个列表或一个用户数组(我尝试了这两种方法,它们都返回了相同的错误):
private User[] getAllUsers() {
ResponseEntity<User[]> response = restTemplate.getForEntity(
"/users",
User[].class
);
return response.getBody();
}
但我得到以下错误:
org.springframework.web.client.RestClientException: Error while extracting response for type [class [Lhu.bme.aut.druk.first.domain.User;] and content type [application/json]; nested exception is org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize instance of `[Lhu.bme.aut.druk.first.domain.User;` out of START_OBJECT token; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `[Lhu.bme.aut.druk.first.domain.User;` out of START_OBJECT token
at [Source: (PushbackInputStream); line: 1, column: 1]
如果有人知道问题的原因,我会非常感谢你的帮助。谢谢您!
1条答案
按热度按时间tmb3ates1#
正如您在提供的json内容中看到的,方法的响应不是列表或数组。它是一个物体。
这行不通。必须创建一个新类,如下所示: