我写了一个货币转换程序
JSON
从…起
api.fixer.io
,映射对象并创建选定速率的简单数据集。
Jackson
解析和映射对象,并将其替换为
RestTemplate
.
它可以很好地读取基础货币和日期,但不能
Rates
子对象。为什么?
我的代码:
Currency
类别:
package com.github.gromo13.currencyConverter.model.util;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public class Currency {
private String base;
private String date;
private Rates rates;
public Currency() {
}
public String getBase() {
return this.base;
}
public void setBase(String base) {
this.base = base;
}
public String getDate() {
return this.date;
}
public void setDate(String date) {
this.date = date;
}
public Rates getRates() {
return this.rates;
}
public void setRates(Rates rates) {
this.rates = rates;
}
public double getRate(String currencyCode) {
return rates.getRate(currencyCode);
}
}
费率
类别:
package com.github.gromo13.currencyConverter.model.util;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public class Rates {
private double eur;
private double pln;
private double usd;
public double getEur() {
return this.eur;
}
public void setEur(double eur) {
this.eur = eur;
}
public double getPln() {
return this.pln;
}
public void setPln(double pln) {
this.pln = pln;
}
public double getUsd() {
return this.usd;
}
public void setUsd(double usd) {
this.usd = usd;
}
public double getRate(String currencyCode) {
currencyCode = currencyCode.toUpperCase();
switch (currencyCode) {
case "EUR":
return this.eur;
case "PLN":
return this.pln;
case "USD":
return this.usd;
default:
return 1;
}
}
}
Repository
必须映射的类
通货
对象使用
RestTemplate
:
package com.github.gromo13.currencyConverter.repository;
import com.github.gromo13.currencyConverter.model.util.Currency;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.web.client.RestTemplate;
@Repository
public class FixerIoCurrencyRepository implements CurrencyRepository {
@Autowired
private RestTemplate restTemplate;
public void setRestTemplate(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
@Override
public Currency getCurrency(String currencyCode) {
Currency currency = restTemplate.getForObject("http://api.fixer.io/latest?base={currencyCode}", Currency.class, currencyCode);
return currency;
}
}
Sample JSON data I am trying to parse and map
我在用这个
通货
要准备的对象
DataSet
对象的简单映射
<currencyName, rate>
并将其打印到视图中的表中。一切都很好,我每次都收到
0
作为每种货币的汇率。