【发布时间】:2019-08-20 04:50:29
【问题描述】:
我正在尝试制作在线歌唱家。我需要从外部 API 获取具有货币价值的表格,正是从该页面:http://api.nbp.pl/api/exchangerates/tables/A?format=json 我想在货币课上得到答案。有人可以帮我完成这项任务吗?
@Service
public class CurrentFromNBPImpl implements CurrentFromNBP {
@Override
public Currency getValueOfCurrency(String currencyCode) throws WrongCurrencyCode {
Currency currency = null;
try {
URL url = new URL("http://api.nbp.pl/api/exchangerates/tables/A?format=json");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type", "application/json");
if (connection.getResponseCode() == 404)
throw new WrongCurrencyCode(currencyCode);
InputStreamReader inputStreamReader = new InputStreamReader(connection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String jsonOutput = bufferedReader.readLine();
connection.disconnect();
ObjectMapper objectMapper = new ObjectMapper();
Currency list = objectMapper.readValue(jsonOutput, Currency.class);
System.out.println(list);
} catch (IOException e) {
e.printStackTrace();
}
assert false;
return currency;
}
}
@Data
public class Currency {
@JsonProperty("table")
private String table;
@JsonProperty("no")
private String no;
@JsonProperty("effectiveDate")
private String effectiveDate;
@JsonProperty("rates")
private List<Rate> rates = null;
}
@Data
public class Rate {
@JsonProperty("currency")
private String currency;
@JsonProperty("code")
private String code;
@JsonProperty("mid")
private Double mid;
}
日志:
com.fasterxml.jackson.databind.exc.MismatchedInputException:无法从 START_ARRAY 令牌中反序列化 com.kolej.bartosz.challenge.domain.Currency 的实例
在 [Source: (String)"[{"table":"A","no":"062/A/NBP/2019","effectiveDate":"2019-03-28","rates":[{ "currency":"bat (Tajlandia)","code":"THB","mid":0.1202},{"currency":"dolar amerykański","code":"USD","mid":3.8202} ,{"currency":"dolar australijski","code":"AUD","mid":2.7098},{"currency":"dolar Hongkongu","code":"HKD","mid":0.4867} ,{"currency":"dolar kanadyjski","code":"CAD","mid":2.8461},{"currency":"dolar nowozelandzki","code":"NZD","mid":2.6006} ,{"currency":"dolar singapurski","code":"SGD","mid":2.8179},{"currency":"eu"[截断 1616 个字符];行:1,列:1]
【问题讨论】:
-
这里有什么不清楚的地方?你说杰克逊你的 JSON 将是一个单一的
Currency对象,但它不是。