daer
daer

Reputation: 25

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

Upvotes: 0

Views: 1877

Answers (2)

luk2302
luk2302

Reputation: 57214

You need a

class ResultContainer {
    Student[] allStudents;
}

and then parse the result as

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

Upvotes: 2

Korgen
Korgen

Reputation: 5409

You need to parse the outer object.

Add another class

public class StudentList {
  List<Student> allStudents;
}

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

Upvotes: 2

Related Questions