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

SpringBoot中使用@GetMapping调用第三方服务接口将JSON转换为List失败的技术求助

Fixing the 500 Error & JSON Parsing Issue with RestTemplate

Hey there, let's tackle this frustrating problem step by step. The error you're seeing has two key parts: a 500 Internal Server Error from the target service and a Gson parsing issue (Not a JSON Object: null). Here's how to diagnose and fix it:

1. First, Figure Out What the Target Service Is Actually Returning

A 500 error means the service at baseUrl is throwing an internal exception—so it's not even sending back the JSON list you're expecting. Let's capture its actual response:

Update your code to catch the error and print the full response body. This will tell you exactly what the target service is sending (instead of just seeing the exception stack trace):

@GetMapping(value="/restDeneme", produces="application/json")
public List<Orders> getOrders(){
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    HttpEntity<String> entity = new HttpEntity<String>(headers);
    
    try {
        ResponseEntity<List<Orders>> response = restTemplate.exchange(
            baseUrl , HttpMethod.GET,entity, new ParameterizedTypeReference<List<Orders>>() {});
        return response.getBody();
    } catch (HttpServerErrorException e) {
        // Print the exact error from the target service
        System.err.println("Target Service Status Code: " + e.getStatusCode());
        System.err.println("Target Service Error Response: " + e.getResponseBodyAsString());
        throw e; // Re-throw or handle based on your business needs
    }
}

Run this and check the console—you'll likely see an error message from the target service explaining why it's failing (like a database issue, missing parameter, etc.). Fixing that service's internal error is the first priority.

2. Verify Your RestTemplate JSON Converter Configuration

The Gson error suggests your RestTemplate might be using Gson for parsing, but it's not set up to handle list types correctly. Here's how to configure it properly:

If you're using Gson, make sure your RestTemplate bean uses GsonHttpMessageConverter and has a properly configured Gson instance:

@Bean
public RestTemplate restTemplate() {
    RestTemplate restTemplate = new RestTemplate();
    
    // Remove default Jackson converter (if present) and add Gson's
    List<HttpMessageConverter<?>> converters = restTemplate.getMessageConverters();
    converters.removeIf(converter -> converter instanceof MappingJackson2HttpMessageConverter);
    
    // Configure Gson to handle nulls and collections
    Gson gson = new GsonBuilder()
        .serializeNulls()
        .setDateFormat("yyyy-MM-dd'T'HH:mm:ss") // Match target service's date format if needed
        .create();
    
    converters.add(new GsonHttpMessageConverter(gson));
    return restTemplate;
}

3. Ensure Your Orders Class Matches the Target JSON Structure

Even if the target service starts returning a valid list, parsing will fail if your Orders class doesn't align with the JSON objects:

  • Field names: If the target service uses snake_case (like order_id) but your class uses camelCase (orderId), add Gson's @SerializedName annotation to map them:
    public class Orders {
        @SerializedName("order_id")
        private Long orderId;
        // Other fields, getters, setters
    }
    
  • No-arg constructor: Make sure Orders has a public no-argument constructor—Gson requires this to instantiate objects during deserialization.
  • Field types: Double-check that all field types (String, Long, Boolean, etc.) match the JSON values from the target service.

4. Handle Empty/Null Responses Gracefully

If the target service might return an empty list or null, update your code to avoid null pointer issues:

ResponseEntity<List<Orders>> response = restTemplate.exchange(
    baseUrl , HttpMethod.GET,entity, new ParameterizedTypeReference<List<Orders>>() {});
List<Orders> orders = response.getBody();
return orders != null ? orders : Collections.emptyList();

Final Note

Start with step 1—most likely the target service is broken and sending back an error JSON (or null) instead of the list you expect. Once you fix that service's internal 500 error, the parsing issues should resolve themselves (assuming your converter and Orders class are correctly set up).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 15:37:44