如何在简单的 Spring 引导应用程序中使用嵌套对象数组反序列化 Json

How to deserialize Json with a nested array of objects in a simple Spring Boot application

Json POST 请求如下所示:

   {
   'title':'Star Wars: The Empire Strikes Back',
   'description':'Darth Vader is adamant about turning Luke Skywalker to the dark side.',
   'actors':[
      {
         'lastName':'Ford',
         'name':'Harrison'
      },
      {
         'lastName':'Hamill',
         'name':'Mark'
      }
   ]
  }

所以我的 Spring 启动应用程序只是想将整个 json 作为“电影”class 存储,并且在它里面有一个内联的“演员”数组。这是电影模型:

    @Entity
    public class Film {

      @Id
      @GeneratedValue
      private long id;
      private String title;
      private String description;
    
      private ArrayList<Actor> actors = new ArrayList<>();

我有一个看起来类似的 Actor 的单独实体:

    @Entity
    public class Actor {

      @Id
      @GeneratedValue
      private long id;
      private String name;
      private String lastName;

最后,我在控制器的 PostMapping 中使用了 RequestBody Annotation:

    @PostMapping(value= "/api/film")
    @ResponseStatus(HttpStatus.CREATED)
    public Film addFilm(@RequestBody Film film) {
       service.createFilm(film);
       return film;

问题是我总是收到 Actor 无法序列化的 java.io.NotSerializableException。我尝试将 Actor 设为 Static inline class,但这并没有改变任何东西。有人知道这里出了什么问题吗?

您的 Actor class 需要实现 Serializable。

@Entity
public class Actor implements Serializable{

  @Id
  @GeneratedValue
  private long id;
  private String name;
  private String lastName;