RestTemplate结果不能反序列化



我试图在Springboot中使用外部API,但我不知道如何将resttemplate结果转换为列表。

示例JSON数据

"posts": [
{ "id": 1,
"author": "Rylee Paul",
"authorId": 9,
"likes": 960,
"popularity": 0.13,
"reads": 50361,
"tags": [ "tech", "health" ]
},

Post实体类

private int id;
private String author;
private int authorId;
private int likes;
private double popularity;
private long reads;
@JsonFormat(with = JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY)
private List<String> tags; 

服务类

ResponseEntity<Post []> responseEntity =restTemplate.getForEntity(url,Post[].class,tagName);
Post [] posts=responseEntity.getBody();

getForEntity()方法抛出以下异常

com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize value of type `[Lcom.example.demo.data.Post;` from Object value (token `JsonToken.START_OBJECT`)

我花了很多时间调试它,在网上搜索,但我不能解决它。有人能帮我一下吗?我很感激!

问题是JSON数据是对象的形式,但是您要求它反序列化一个数组。一个可能的解决方案是创建一个包装器类:

public class PostsResponse {
private Post[] posts;
public Post[] getPosts() {
return posts;
}
}

像这样访问:

ResponseEntity<PostsResponse> responseEntity =
restTemplate.getForEntity(url, PostsResponse.class, tagName);
PostsResponse responseBody = responseEntity.getBody();
if (responseBody != null) {
Post[] posts = responseBody.getPosts();
}

您可以为Post.java创建一个包装器类

public class Posts {
private List<Post> posts;

//getters and setters or Lombok

}

ResponseEntity<Posts> responseEntity =restTemplate.getForEntity(url,Posts.class);

您的JSON数据包有posts数组由一些其他对象包围。你的映射对象结构应该是:

public class Posts {
private List<Post> posts;
// getters and setters
}

最新更新