簡體   English   中英

如何在簡單的 Spring Boot 應用程序中使用嵌套的對象數組反序列化 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 Boot 應用程序只想將整個 json 存儲為“Film”類,並在其中包含一個“Actors”內聯數組。 這是電影模型:

    @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 成為靜態內聯類,但這並沒有改變任何東西。 有人知道這里有什么問題嗎?

您的 Actor 類需要實現 Serializable。

@Entity
public class Actor implements Serializable{

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM