英文:
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" 的内联数组。以下是 Film 模型:
@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 注解:
@PostMapping(value= "/api/film")
@ResponseStatus(HttpStatus.CREATED)
public Film addFilm(@RequestBody Film film) {
service.createFilm(film);
return film;
问题在于,我总是得到 java.io.NotSerializableException,指示 Actor 无法序列化。我尝试将 Actor 声明为静态内联类,但这并没有改变任何情况。有人知道这里出了什么问题吗?
英文:
The Json POST request looks like this:
{
'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'
}
]
}
So my Spring Boot Application just wants to store this whole json as a "Film" class and inside it has an inline array of "Actors". Here is the Film model:
@Entity
public class Film {
@Id
@GeneratedValue
private long id;
private String title;
private String description;
private ArrayList<Actor> actors = new ArrayList<>();
I have a separate entity for the Actor that looks similar:
@Entity
public class Actor {
@Id
@GeneratedValue
private long id;
private String name;
private String lastName;
Finally, I am using the RequestBody Annotation in the PostMapping in the Controller:
@PostMapping(value= "/api/film")
@ResponseStatus(HttpStatus.CREATED)
public Film addFilm(@RequestBody Film film) {
service.createFilm(film);
return film;
The problem is I always get the java.io.NotSerializableException that Actor cannot be serialized. I tried making Actor a Static inline class but that did not change anything. Anyone have an idea what is wrong here ?
答案1
得分: 0
你的 Actor 类需要实现 Serializable。
@Entity
public class Actor implements Serializable{
@Id
@GeneratedValue
private long id;
private String name;
private String lastName;
英文:
Your Actor class needs to implement Serializable.
@Entity
public class Actor implements Serializable{
@Id
@GeneratedValue
private long id;
private String name;
private String lastName;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论