Spring RestTemplate 将 JSON 响应映射到 Map 抛出 MismatchedInputException

问题描述

我正在尝试将 Github 的提交详细信息 API 中的 JSON 解析为 HashMap。我在测试中使用的示例 Json 是 here

测试代码是

@SpringJUnitConfig(classes = {GithubApiService.class,RestTemplateConfiguration.class})
@EnableAutoConfiguration
public class GithubApiServiceTest {

    @Test
    public void testGithubResponseJsonToMapConversion(
            @Autowired RestTemplate restTemplate,@Autowired GithubApiService service,@Value("classpath:github/commit-payload.json") Resource commitPayloadFile) throws IOException {

        final String COMMITS_URL = "https://api.github.com/repos/Codertocat/Hello-World/commits/sha";

        //Stub response from Github Server
        String responseJson = new ObjectMapper().writeValueAsString(
                new String(Files.readAllBytes(Paths.get(commitPayloadFile.getFile().getAbsolutePath()))));
        MockRestServiceServer mockGithubServer = MockRestServiceServer.createServer(restTemplate);
        mockGithubServer.expect(requestTo(COMMITS_URL))
                .andRespond(withSuccess().contentType(APPLICATION_JSON).body(responseJson));

        //Call API Service
        Map<String,Object> result = service.getCommitDetails(COMMITS_URL);
        //Expect return type is hashmap
        assertThat(result.get("sha")).isEqualTo("6dcb09b5b57875f334f61aebed695e2e4193db5e");
    }
}

服务代码是

@Service
@AllArgsConstructor(onConstructor = @__(@Autowired))
public class GithubApiService {

    @Autowired
    private final RestTemplate restTemplate;

    public Map<String,Object> getCommitDetails(String commitsUrl) {
        ParameterizedTypeReference<Map<String,Object>> responseType = new ParameterizedTypeReference<Map<String,Object>>() {
        };
        RequestEntity<Void> request = RequestEntity.get(URI.create(commitsUrl)).accept(APPLICATION_JSON).build();
        return restTemplate.exchange(request,responseType).getBody();
    }
}

这无法将 JSON 响应转换为 Map,并出现以下错误 (full log here)

Caused by: com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `java.util.LinkedHashMap` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('{
  "url": "https://api.github.com/repos/octocat/Hello-World/commits/6dcb09b5b57875f334f61aebed695e2e4193db5e","sha": "6dcb09b5b57875f334f61aebed695e2e4193db5e","node_id": "MDY6Q29tbWl0NmRjYjA5YjViNTc4NzVmMzM0ZjYxYWViZWQ2OTVlMmU0MTkzZGI1ZQ==","html_url": "https://github.com/octocat/Hello-World/commit/6dcb09b5b57875f334f61aebed695e2e4193db5e","comments_url": "https://api.github.com/repos/octocat/Hello-World/commits/6dcb09b5b57875f334f61aebed695e2e4193db5e/comments",

由于我使用 spring-boot-starter-web,它会自动连接包括 MappingJackson2HttpMessageConverter 在内的转换器,但调试器显示响应正在由 ByteArrayHttpMessageConverter 处理,尽管将内容类型设置为 application/json .

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)