0

I'm working on a Java project that fetches the URL of the most popular clips of the day on Twitch. To do this I'm sending a request to the twitch API with this code:

    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;
    }
}

which returns a json file that looks like this:

{"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"}}

Although, I'm getting this error:

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
Auties01
  • 29
  • 1
  • 9

1 Answers1

0

As you can see from your json with the { data: [{...}, {...}, {...}], pagination: {...} }, you get a object. You tried to read a array, but not the object that is given. This object has an array data and an object pagination.

Assuming that your object TwitchData only contains the attributes from the data array, you could work with the following solution.

class Result {
    TwitchData[] data;
    Pagination pagination;
}

class Pagination{
    String cursor;
}

After you created the two classes, you can now read the json.

Result r = gson.fromJson(new FileReader(out), Result.class);
return r.data;

This will return you the data array which can also be transfomed into a List if you wish so.

alea
  • 980
  • 1
  • 13
  • 18