我創建了一個簡單的 Spring Boot 應用程式,我在其中嘗試通過 JSON 資訊使用 API。下面你可以看到我在服務類上使用 RestTemplate 創建的簡單代碼。我面臨的問題是,當我使用下面的 API url 時,我得到了以下嵌套例外。

如果我使用資訊較少的 API url,一切正常。我究竟做錯了什么?
控制器類
package com.andrekreou.iot;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class RestSpringBootController {
private final Service service;
@Autowired
public RestSpringBootController(Service service) {
this.service = service;
}
@GetMapping(path = "/opap")
public List<Object> getWeather(){
return service.getWeather();
}
}
服務等級
package com.andrekreou.iot;
import org.springframework.web.client.RestTemplate;
import java.util.Arrays;
import java.util.List;
@org.springframework.stereotype.Service
public class Service {
public List<Object> getWeather(){
String url = "https://api.opap.gr/draws/v3.0/5104/last-result-and-active";
RestTemplate restTemplate = new RestTemplate();
Object[] weather = restTemplate.getForObject(url, Object[].class);
return Arrays.asList(weather);
}
}
uj5u.com熱心網友回復:
問題出在這行代碼中:
Object[] weather = restTemplate.getForObject(url, Object[].class);
您正在映射此 JSON :
{
"last": {
"gameId": 5104,
"drawId": 2446,
"drawTime": 1653850800000,
"status": "results",
"drawBreak": 1800000,
"visualDraw": 2446,
"pricePoints": {
"amount": 0.5
},
"winningNumbers": {
"list": [
1,
9,
19,
22,
33
],
"bonus": [
1
]
},
...
}
哪個不是陣列,它是一個物件,這就是您在問題中描述錯誤的原因。
將上面的代碼行更改為:
Object weather = restTemplate.getForObject(url, Object.class);
它應該可以正常作業。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/489159.html
上一篇:將值傳遞到例外字串訊息中
