Search code examples
javajsonspring-bootresttemplate

How to consume an external API in Spring Boot


I want to consume Json from an API. the API looks like this:

{
  "allStudents": [
    {
      "fname": "Jack",
      "age": 22,
      "courses": {
        "name": "AI"
      }
    },
    {
     ..
    },
    ..
  ]
}

I am struggling with the fact that all the data are in an array.

I created a Student Class

public class Student {
    private String name;
    private int age;
    private List<Course> courses;
}

with all the getters and setters.

How to consume data from this API ?

I tried the following :

Student[] students= restTemplate.getForObject(url, Student[].class);

But this is not working and giving an error JSON parse error: Cannot deserialize instance of Student out of START_OBJECT token


Solution

  • You need to parse the outer object.

    Add another class

    public class StudentList {
      List<Student> allStudents;
    }
    

    and then use .getForObject(url, StudentList.class);