未报告的 IOException



请帮助我。我正在尝试从 json 文件中读取数据并将它们存储在 java 对象中。这是代码:

try {
    ObjectMapper mapper2 = new ObjectMapper();
    File file2 = new File("Lessons.json");
    List<Lesson> lessonList = Arrays.asList(mapper2.readValue(file2, Lesson[].class));
}catch (Exception e) {
    e.printStackTrace();
}

但是它向我显示了错误:

Error   unreported exception java.io.IOException; must be caught or declared to be thrown   

在我创建对象列表的行中。

我可以看到您的try-catch直接在 A 类下。请确保它在任何方法中。理想情况下,它不应该显示上述错误catch (Exception e)因为块已经存在。下面的示例代码对我来说工作正常。

public static void main(String[] args) {
    try {
        ObjectMapper mapper2 = new ObjectMapper();
        File file2 = new File("Lessons.json");
        List<Lesson> lessonList = Arrays.asList(mapper2.readValue(file2, Lesson[].class));
    } catch (Exception e) {
        e.printStackTrace();
    }
}

最新更新