You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot调用API遇反序列化错误:数组转对象失败求助

问题解决:正确接收字符串数组API响应

错误根源

你调用的API返回的是JSON字符串数组,但最初用jokeResponse.class接收——这个类是为解析键值对形式的JSON对象设计的,类型完全不匹配,因此触发反序列化错误。你之前尝试String[].class的方向是对的,但大概率没同步修改方法的返回类型,导致问题没解决。

正确实现方案

以下是两种可行的实现方式:

方式1:返回String数组

直接修改方法返回类型为String[],同步调整getForObject的参数:

@Override
public String[] getTypesList() {
    // 建议将RestTemplate注入类中复用,而非每次方法内新建,比如用@Autowired
    RestTemplate restTemplate = new RestTemplate();
    return restTemplate.getForObject("https://official-joke-api.appspot.com/types", String[].class);
}

方式2:返回List

如果更习惯用集合类型,需要用exchange方法配合ParameterizedTypeReference解决泛型类型擦除问题:

import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

@Override
public List<String> getTypesList() {
    RestTemplate restTemplate = new RestTemplate();
    ResponseEntity<List<String>> response = restTemplate.exchange(
            "https://official-joke-api.appspot.com/types",
            HttpMethod.GET,
            null,
            new ParameterizedTypeReference<List<String>>() {}
    );
    return response.getBody();
}

额外建议

  • 不要在每个方法内新建RestTemplate实例,建议在配置类中创建单例Bean,通过@Autowired注入到业务类中复用,提升性能。
  • 可以添加异常捕获(比如RestClientException),处理API调用失败的场景。

内容的提问来源于stack exchange,提问作者knard

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 17:29:58