亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用json將包含多個對象的json文件轉換為java對象列表

如何使用json將包含多個對象的json文件轉換為java對象列表

楊魅力 2023-02-16 15:53:52
我正在開發一個 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;

這將返回數據數組,如果您愿意,也可以將其轉換為列表。


查看完整回答
反對 回復 2023-02-16
  • 1 回答
  • 0 關注
  • 188 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號