为了账号安全,请及时绑定邮箱和手机立即绑定

如何使用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 关注
  • 170 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号