使用GSON将JSON反序列化为Java对象时出现问题

fhg3lkii  于 2022-11-06  发布在  Java
关注(0)|答案(2)|浏览(196)

我一直在努力学习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)
bejyjqdl

bejyjqdl1#

您正在反序列化的JSON表示一个对象,该对象上有一个对象列表。您尝试反序列化的Java对象需要与之匹配。
首先,创建一个新的类MovieList

class MovieList {
     List<Movie> movies;
}

将您的Movies类更新为Movie,因为它表示一个电影。

class Movie {
     String name;
     String url;
     String IMAX;
     String rating;
     List<Cast> cast;
}

现在,尝试使用以下命令调用gson.fromJson(...)

MovieList movieList = gson.fromJson(new FileReader("src/main/input.json"), MovieList.class);
System.out.println(movieList.getMovies().get(0));
mccptt67

mccptt672#

尝试使用此

Gson gson = new Gson();
Movies[] movies = gson.fromJson(new JsonReader(new FileReader("src/main/input.json"))),Movies[].class);

或类似的东西

Type listType = new TypeToken<List<Movies>>() {}.getType();
List<Movies> movies = new Gson().fromJson(new JsonReader(new FileReader("src/main/input.json"))), listType);

相关问题