我一直在努力学习GSON,但我一直在努力。我正在尝试使用GSON将JSON文件反序列化为Java对象。我在这里读过无数其他问题,但我一辈子都不明白我做错了什么。
下面是我的JSON文本:
{
"movies": [
{
"name": "The Shawshank Redemption",
"url": "https://parsehub.com/sandbox/moviedetails?movie=The%20Shawshank%20Redemption",
"IMAX": "06:00 PM",
"rating": "9 . 2",
"cast": [
{
"character": "Andy Dufresne",
"actor": "Tim Robbins"
},
{
"character": "Ellis Boyd 'Red' Redding",
"actor": "Morgan Freeman"
},
{
"character": "Warden Norton",
"actor": "Bob Gunton"
},
{
"character": "Heywood",
"actor": "William Sadler"
}
]
},
{
"name": "Schindler's List",
"url": "https://parsehub.com/sandbox/moviedetails?movie=Schindler%27s%20List",
"IMAX": "06:15 PM",
"rating": "8 . 9",
"cast": [
{
"character": "Oskar Schindler",
"actor": "Liam Neeson"
},
{
"character": "Itzhak Stern",
"actor": "Ben Kingsley"
},
{
"character": "Amon Goeth",
"actor": "Ralph Fiennes"
}
]
}
]
}
下面是我的Java代码:
import com.google.gson.Gson;
import java.io.*;
import java.lang.reflect.Type;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
Gson gson = new Gson();
Movies[] movies = gson.fromJson(new FileReader("src/main/input.json"), (Type) Movies.class);
System.out.println(movies[0]);
}
class Movies {
String name;
String url;
String IMAX;
String rating;
ArrayList<Cast> cast;
}
class Cast {
ArrayList<CastMember> castMembers;
}
class CastMember{
String character;
String actor;
}
}
当我运行这个程序时,我得到以下错误:
Exception in thread "main" java.lang.ClassCastException: class com.Main$Movies cannot be cast to class [Lcom.Main$Movies; (com.Main$Movies and [Lcom.Main$Movies; are in unnamed module of loader 'app')
at com.Main.main(Main.java:13)
2条答案
按热度按时间bejyjqdl1#
您正在反序列化的JSON表示一个对象,该对象上有一个对象列表。您尝试反序列化的Java对象需要与之匹配。
首先,创建一个新的类
MovieList
。将您的
Movies
类更新为Movie
,因为它表示一个电影。现在,尝试使用以下命令调用
gson.fromJson(...)
mccptt672#
尝试使用此
或类似的东西