gpt4 book ai didi

java - SpringFramework ResponseBody 返回具有空值的对象

转载 作者:行者123 更新时间:2023-12-02 11:56:46 28 4
gpt4 key购买 nike

我有一个 RestController,它将 Film 对象列表发送回用户:

@RestController
@RequestMapping("/view")
public class FilmRestController {

@RequestMapping(value = "/", method = RequestMethod.GET, produces = "application/json")
public @ResponseBody List<Film> getCurrentFilms(){
FilmInfo filmInfo = new FilmInfo();
return filmInfo.getCurrentFilms();
}
}

每个 Film 对象包含两个字符串(标题、导演)和 Actor 列表。所以相当简单的pojo。

当我在 Postman 中执行请求时,我收到以下响应:

[
{
"title": null,
"director": null,
"actors": null
},
{
"title": null,
"director": null,
"actors": null
},
{
"title": null,
"director": null,
"actors": null
},
{
"title": null,
"director": null,
"actors": null
}
]

我一开始以为这是一个小故障,所以我后来编写了以下方法:

@RequestMapping(value = "/getOneFilm", method = RequestMethod.GET,  produces = "application/json")
public @ResponseBody Film getOneFilm(){
Film film = new Film("The Shawshank Redemption", "Frank Darabont", Arrays.asList("Tim Robbins","Morgan Freeman","Bob Gunton"));
return film;
}

果然我的回应是:

{
"title": null,
"director": null,
"actors": null
}

根据要求,这是我的电影类(class):

package entities;

import java.util.List;

public class Film {

private String title;
private String director;
private List<String> actors;

public Film(String title, String director, List<String> actors) {
title = this.title;
director = this.director;
actors = this.actors;
}


public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDirector() {
return director;
}
public void setDirector(String director) {
this.director = director;
}
public List<String> getActors() {
return actors;
}
public void setActors(List<String> actors) {
this.actors = actors;
}
}

是否有原因导致 ResponseBody 无法将我的对象转换为在响应中发回?我应该改变策略并手动执行 JSON 序列化程序吗?我

最佳答案

在构造函数中,您正在更新参数而不是属性:

public Film(String title, String director, List<String> actors) {
title = this.title;
director = this.director;
actors = this.actors;
}

类中的属性保持为空。将其更改为:

public Film(String title, String director, List<String> actors) {
this.title = title;
this.director = director;
this.actors = actors;
}

关于java - SpringFramework ResponseBody 返回具有空值的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47556217/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com