Home > database >  RestTemplate result cannot be deserialized
RestTemplate result cannot be deserialized

Time:10-06

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!

CodePudding user response:

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

}

CodePudding user response:

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();
}

CodePudding user response:

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);
  • Related