繁体   English   中英

当我尝试将 JSON 作为 Object 返回时,我收到“提取类型响应时出错”。 我该如何解决这个问题?

[英]I'm recieving "Error while extracting response for type" when I try to return the JSON as an Object. How can I solve this?

I'm doing an API that consumes an external API ( https://swapi.dev/ ), but I'm receving this error when I try to return the JSON converted to Object.

我试图解决这个问题将近 12 个小时,但没有任何成功 x_x

Error while extracting response for type [class [Lcom.starwarsapi.filmsapi.model.FilmModel;] and content type [application/json]; nested exception is org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type `[Lcom.starwarsapi.filmsapi.model.FilmModel;` from Object value (token `JsonToken.START_OBJECT`);

电影控制器:

@RestController
@RequestMapping("/films")
public class FilmController {

    @Autowired
    private FilmService filmService;

    @GetMapping
    public List<FilmModel> getAllFilms() {
        List<FilmModel> response = filmService.getAllFilms();
        return response;
    }

电影型号:

@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class FilmModel {
    private FilmResultModel[] results;
}

电影结果模型

@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class FilmResultModel {
    private String title;

    @JsonProperty("episode_id")
    private Integer episodeId;

    @JsonProperty("opening_crawl")
    private String description;

    private String director;
    private String producer;

    @JsonProperty("release_date")
    private String releaseData;

    private String[] characters;
    private String[] planets;
    private String[] starships;
    private String[] vehicles;
    private String[] species;
    private String created;
    private String edited;
    private String url;

电影服务:

public interface FilmService {
    public List<FilmModel> getAllFilms();
}

FilmServiceImpl:

@Service
public class FilmServiceImpl implements FilmService {

    @Value("${external.api.url}")
    private String filmBaseUrl;

    @Autowired
    private RestTemplate restTemplate;

    @Override
    public List<FilmModel> getAllFilms() {
        FilmModel[] result = restTemplate.getForObject(filmBaseUrl, FilmModel[].class);
        List<FilmModel> films = Arrays.asList(result);
        System.out.println(films);
        return films;
    }

PS¹: external.api.url .api.url = https://swapi.dev/api/films/?format=json

PS²:当我将getAllFilms作为字符串返回时,程序运行:

@Override
public String getAllFilms() {
    String result = restTemplate.getForObject(filmBaseUrl, String.class);
    System.out.println(result);

    return result;
}

但我需要它以 object 的形式返回,因为稍后我将尝试创建一个 PUT 方法来更改电影的描述。

尝试使用FilmModel result = restTemplate.getForObject(filmBaseUrl, FilmModel.class);

FilmModel 只是外包装 object 并包含电影列表。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM