java - "Cannot deserialize instance of"来自外部API

标签 java json

我正在尝试制作在线领唱。我需要从外部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 token 中反序列化 com.kolej.bartosz.challenge.domain.Currency 的实例 在[来源:(字符串)”[{“表”:“A”,“否”:“062/A/NBP/2019”,“有效日期”:“2019-03-28”,“费率”:[{ "currency":"bat (Tajlandia)","code":"THB","mid":0.1202},{"currency":"dolar amerykański","code":"USD","mid":3.8202} ,{"currency":"澳大利亚币","code":"AUD","mid":2.7098},{"currency":"香港币","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 对象是一个 jsonArray。您需要反序列化为 Currency 列表,而不是 Currency

关于java - "Cannot deserialize instance of"来自外部API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55414161/

相关文章:

java - 萨克斯字符将元素分开

python - urllib2.urlopen addinfol 实例没有属性 '__getitem__'

json - 当键是数字字符串时使用jq从json获取数据

java - 数组的 equal 方法如何工作?

java - 为什么我的 Eclipse 设置不能与 Maven 插件一起使用?

java - Beanshell 模式匹配器正则表达式

python - 在 Python 中打印浮点值(Mapbox 地理坐标)

javascript - 在JS中记录HTTP请求的字节大小

java - 如何在插入记录时使用 spring jdbctemplate batchupdate 覆盖?

java - 泛型类型参数边界和具体类