0

我正在开发一个 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;
    }
}

它返回一个如下所示的 json 文件:

{"data":[{"id":"HeadstrongObservantEagleANELE","url":"https://clips.twitch.tv/HeadstrongObservantEagleANELE","embed_url":"https://clips.twitch.tv/embed?clip=HeadstrongObservantEagleANELE","broadcaster_id":"81687332","broadcaster_name":"cloakzy","creator_id":"158774890","creator_name":"xvibes","video_id":"442904759","game_id":"33214","language":"en","title":"creatorcode: cloakzy !mouse","view_count":11755,"created_at":"2019-06-23T01:05:51Z","thumbnail_url":"https://clips-media-assets2.twitch.tv/34634505760-offset-684-preview-480x272.jpg"},{"id":"LongSpineyYakinikuPogChamp","url":"https://clips.twitch.tv/LongSpineyYakinikuPogChamp","embed_url":"https://clips.twitch.tv/embed?clip=LongSpineyYakinikuPogChamp","broadcaster_id":"81687332","broadcaster_name":"cloakzy","creator_id":"57403631","creator_name":"4rchr","video_id":"442904759","game_id":"33214","language":"en","title":"x","view_count":10204,"created_at":"2019-06-23T01:08:48Z","thumbnail_url":"https://clips-media-assets2.twitch.tv/34634505760-offset-860-preview-480x272.jpg"},{"id":"SuspiciousMistyTortoiseImGlitch","url":"https://clips.twitch.tv/SuspiciousMistyTortoiseImGlitch","embed_url":"https://clips.twitch.tv/embed?clip=SuspiciousMistyTortoiseImGlitch","broadcaster_id":"81687332","broadcaster_name":"cloakzy","creator_id":"139090954","creator_name":"Malgre","video_id":"442904759","game_id":"33214","language":"en","title":"cloak","view_count":8104,"created_at":"2019-06-23T01:12:36Z","thumbnail_url":"https://clips-media-assets2.twitch.tv/AT-cm%7C481623363-preview-480x272.jpg"}],"pagination":{"cursor":"eyJiIjpudWxsLCJhIjp7IkN1cnNvciI6Ik13PT0ifX0"}}

虽然,我收到了这个错误:

Exception in thread "Timer-0" com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $
    at com.google.gson.Gson.fromJson(Gson.java:939)
    at com.google.gson.Gson.fromJson(Gson.java:892)
    at video.TwitchVideo.getVideoList(TwitchVideo.java:104)
    at video.TwitchVideo.<init>(TwitchVideo.java:19)
    at main.TwitchApplication$1.run(TwitchApplication.java:56)
    at java.util.TimerThread.mainLoop(Unknown Source)
    at java.util.TimerThread.run(Unknown Source)
Caused by: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $
    at com.google.gson.stream.JsonReader.beginArray(JsonReader.java:350)
    at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:80)
    at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:61)
    at com.google.gson.Gson.fromJson(Gson.java:927)
    ... 6 more
4

1 回答 1

0

正如您从带有 的 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;

这将为您返回数据数组,如果您愿意,也可以将其转换为列表。

于 2019-06-23T17:12:32.217 回答