如何使用 json 将包含多个对象的 json 文件转换为 java 个对象的列表

How to convert a json file that contains multiple objects to a list of java objects using json

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

哪个 returns 一个 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.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

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

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