使用 RestTemplate 调用外部 api 时,我有点卡住了,因为我的请求返回一个字符串。我来自 js 背景,所以使用 js 我只会返回 json 并提取我需要的内容。
我只想获取当天(2020-02-07)的股票信息,我不需要元数据等
我的代码:
RestTemplate restTemplate = new RestTemplate();
String result = restTemplate.getForObject(uri, String.class);
return result;
代码返回:
"Meta Data": {
"1. Information": "Daily Prices (open, high, low, close) and Volumes",
"2. Symbol": "XYL",
"3. Last Refreshed": "2020-02-07",
"4. Output Size": "Compact",
"5. Time Zone": "US/Eastern"
},
"Time Series (Daily)": {
"2020-02-07": {
"1. open": "83.3600",
"2. high": "84.9100",
"3. low": "83.1300",
"4. close": "84.2000",
"5. volume": "2495921"
},
"2020-02-06": {
"1. open": "81.0000",
"2. high": "83.3100",
"3. low": "80.8000",
"4. close": "83.1200",
"5. volume": "5052421"
}
我只希望我的请求返回当天:
"2020-02-07": {
"1. open": "83.3600",
"2. high": "84.9100",
"3. low": "83.1300",
"4. close": "84.2000",
"5. volume": "2495921"
}
非常感谢任何帮助!
最佳答案
您需要创建一个 pojo 类,以便可以使用返回的 JSON 并将其映射到 Java 实例。
例如,如果您有类似的内容:
public class TimeSeriesDaily{
@JsonProperty("Time Series (Daily)")
private Map<String, Map<String, String>> dailyValues;
}
然后您可以将其与 RestTemplate 一起使用,如下所示:
TimeSeriesDaily result = restTemplate.getForObject(uri, TimeSeriesDaily.class);
关于java - 使用 Rest Template 从外部 api 返回特定数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60122762/