【问题标题】:How to consume an external API in Spring Boot如何在 Spring Boot 中使用外部 API
【发布时间】:2021-07-16 12:44:33
【问题描述】:

我想通过 API 使用 Json。 API 如下所示:

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

我正在为所有数据都在一个数组中这一事实而苦苦挣扎。

我创建了一个Student Class

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

所有的 getter 和 setter。

如何使用这个 API 的数据?

我尝试了以下方法:

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

但这不起作用并给出错误 JSON parse error: Cannot deserialize instance of Student out of START_OBJECT token

【问题讨论】:

  • 这里你必须解析一个包含学生列表的对象,而不是你正在做的单个学生。
  • 编写一个具有Student[] allStudents 字段的容器类并映射到该对象。
  • @MattiaRighetti 我正在尝试解析一组学生,这是不可能的?
  • 在您的情况下不正确,您必须创建一个具有 Student[] 字段的类,名为 allStudents

标签: java json spring-boot resttemplate


【解决方案1】:

你需要一个

class ResultContainer {
    Student[] allStudents;
}

然后将结果解析为

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

【讨论】:

    【解决方案2】:

    你需要解析外部对象。

    添加另一个类

    public class StudentList {
      List<Student> allStudents;
    }
    

    然后使用.getForObject(url, StudentList.class);

    【讨论】:

      猜你喜欢
      • 2017-11-23
      • 2021-09-17
      • 1970-01-01
      • 1970-01-01
      • 2015-03-28
      • 2020-06-13
      • 2021-11-09
      • 1970-01-01
      • 2019-12-16
      相关资源
      最近更新 更多