我正在開發一個 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
提交
取消