0

I am trying to consume an external API in Springboot, but I cannot figure out how to convert the resttemplate result to a list.

the sample JSON data

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

Post entity class

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; 

Service class

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

getForEntity() method throw the following exception

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

I have spent hours and hours debugging it and searching online, but I cannot solve it. Could someone help me out? I appreciate it!

kiki
  • 62
  • 5
  • 1
    You are looking for an array of Post instances, but your JSON looks like an Object with a field named "posts", which is an array of Post objects. – tgdavies Oct 06 '21 at 04:10

3 Answers3

1

The problem is that the JSON data is in the form of an object, but you are asking it to deserialize an array. One possible solution would be to create a wrapper class:

public class PostsResponse {
    private Post[] posts;

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

Accessed like this:

ResponseEntity<PostsResponse> responseEntity =
        restTemplate.getForEntity(url, PostsResponse.class, tagName);
PostsResponse responseBody = responseEntity.getBody();
if (responseBody != null) {
    Post[] posts = responseBody.getPosts();
}
Tim Moore
  • 8,958
  • 2
  • 23
  • 34
1

You can create a wrapper class for Post.java

public class Posts {

  private List<Post> posts;
  
 //getters and setters or Lombok
 
}

and try

ResponseEntity<Posts> responseEntity =restTemplate.getForEntity(url,Posts.class);
dmca
  • 31
  • 3
0

Your JSON packet is having posts array enclosed by some other objects. So your mapping object structure should be:

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

}
Gaurav Jeswani
  • 4,410
  • 6
  • 26
  • 47