我需要从外部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;
}
log: com.fasterxml.jackson.datind.exc.MismatchedInputException:无法反序列化com.kolej.bartos z.挑战.domain.Currency
的START_ARRAY令牌的实例,位于[Source:(String)"[{"table":"A","no":"062/A/NBP/2019","effectiveDate":"2019-03-28","rate":[{"currency":"bat(Tajlandia)","code":"THB","mid":0.1202},{"currency":"dolar ameryka'ski","code":"USD","mid":3.8202},{"currency":"dolar Australia alijski","code":"AUD","mid":2.7098},{"currency":"dolar Hong kongu","code":"HKD","mid":0.4867},{"currency"SGD","mid2.8179},{"currency":"eu"[截断的1616个字符];第1行,第1列]
您要反序列化的json对象是一个jsonArray。您需要反序列化为Currency
列表,而不是Currency
。
你可以试试这个
ArrayList<Currency> list = new ArrayList<>();
list = objectMapper.readValue(data, new TypeReference<ArrayList<Currency>>() {});