我正在开发一个 Java 项目,该项目获取 Twitch 上当天最流行的剪辑的 URL。为此,我使用以下代码向 twitch API 发送请求: private List<TwitchClip> getVideoList() { try { LocalTime midnight = LocalTime.MIDNIGHT; LocalDate today = LocalDate.now(ZoneId.of("Europe/Berlin")); LocalDateTime todayMidnight = LocalDateTime.of(today, midnight); String formattedStartTime; String formattedEndTime; if(String.valueOf(todayMidnight.getMonthValue()).length() != 2) { formattedStartTime = todayMidnight.getYear() + "-" + 0 + todayMidnight.getMonthValue() + "-" + (todayMidnight.getDayOfMonth() - 1) + "T00:00:00Z"; formattedEndTime = todayMidnight.getYear() + "-" + 0 + todayMidnight.getMonthValue() + "-" + todayMidnight.getDayOfMonth() + "T00:00:00Z"; }else { formattedStartTime = todayMidnight.getYear() + "-" + todayMidnight.getMonthValue() + "-" + (todayMidnight.getDayOfMonth() - 1) + "T00:00:00Z"; formattedEndTime = todayMidnight.getYear() + "-" + todayMidnight.getMonthValue() + "-" + todayMidnight.getDayOfMonth() + "T00:00:00Z"; } URL url = new URL("https://api.twitch.tv/helix/clips?game_id=" + Game.FORTNITE.getId() + "&first=25&started_at=" + formattedStartTime + "&ended_at=" + formattedEndTime); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.addRequestProperty("Client-ID", ""); File out = File.createTempFile(UUID.randomUUID().toString(), ".json"); System.out.println("Downloaded clips data at " + out.getPath()); writeFile(out, connection.getInputStream()); Gson gson = new Gson(); return gson.fromJson(new FileReader(out), new TypeToken<List<TwitchClip>>() { }.getType()); } catch (IOException e) { e.printStackTrace(); return null; }}
1 回答

慕无忌1623718
TA贡献1744条经验 获得超4个赞
从带有 的 json 中可以看出{ data: [{...}, {...}, {...}], pagination: {...} },您得到了一个对象。您试图读取一个数组,但不是给定的对象。这个对象有一个数组data和一个对象pagination。
假设您的对象TwitchData仅包含数据数组中的属性,您可以使用以下解决方案。
class Result {
TwitchData[] data;
Pagination pagination;
}
class Pagination{
String cursor;
}
创建这两个类后,您现在可以读取 json。
Result r = gson.fromJson(new FileReader(out), Result.class);
return r.data;
这将返回数据数组,如果您愿意,也可以将其转换为列表。
添加回答
举报
0/150
提交
取消