繁体   English   中英

如何使用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;
    }
}

它返回一个如下所示的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

正如你可以从你的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;

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM