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

Trouble deserializing JSON into Java objects with GSON

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

试试这个

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);

您正在反序列化的 JSON 表示一个对象,上面有一个对象列表。您尝试反序列化的 Java 对象需要与之匹配。

首先,创建一个新的 class MovieList.

class MovieList {
     List<Movie> movies;
}

将您的 Movies class 更新为 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));