Получаю JSON-файл с https://api.privatbank.ua/p24api/exchange_rates?json&date=01.12.2014, дата не имеет значения в данном случае, она может быть другая, т.к. вводится пользователем с консоли.
Мне нужно вывести только курс доллара, вопрос состоит в том, как мне вытянуть оттуда только курс доллара?
Сам json-файл прилагаю:
{
"date":"01.12.2014",
"bank":"PB",
"baseCurrency":980,
"baseCurrencyLit":"UAH",
"exchangeRate":[
{
"baseCurrency":"UAH",
"currency":"AUD",
"saleRateNB":12.8319250,
"purchaseRateNB":12.8319250
},
{
"baseCurrency":"UAH",
"currency":"CAD",
"saleRateNB":13.2107400,
"purchaseRateNB":13.2107400,
"saleRate":15.0000000,
"purchaseRate":13.0000000
},
{
"baseCurrency":"UAH",
"currency":"CZK",
"saleRateNB":0.6796950,
"purchaseRateNB":0.6796950,
"saleRate":0.8000000,
"purchaseRate":0.6000000
},
{
"baseCurrency":"UAH",
"currency":"DKK",
"saleRateNB":2.5258930,
"purchaseRateNB":2.5258930
},
{
"baseCurrency":"UAH",
"currency":"HUF",
"saleRateNB":0.0612592,
"purchaseRateNB":0.0612592
},
{
"baseCurrency":"UAH",
"currency":"ILS",
"saleRateNB":3.8627380,
"purchaseRateNB":3.8627380,
"saleRate":4.5000000,
"purchaseRate":3.7000000
},
{
"baseCurrency":"UAH",
"currency":"JPY",
"saleRateNB":0.1272593,
"purchaseRateNB":0.1272593,
"saleRate":0.1500000,
"purchaseRate":0.1200000
},
{
"baseCurrency":"UAH",
"currency":"LVL",
"saleRateNB":0.1272593,
"purchaseRateNB":0.1272593
},
{
"baseCurrency":"UAH",
"currency":"LTL",
"saleRateNB":5.4433850,
"purchaseRateNB":5.4433850
},
{
"baseCurrency":"UAH",
"currency":"NOK",
"saleRateNB":2.1609570,
"purchaseRateNB":2.1609570,
"saleRate":2.6000000,
"purchaseRate":2.1000000
},
{
"baseCurrency":"UAH",
"currency":"SKK",
"saleRateNB":2.1609570,
"purchaseRateNB":2.1609570
},
{
"baseCurrency":"UAH",
"currency":"SEK",
"saleRateNB":2.0283750,
"purchaseRateNB":2.0283750
},
{
"baseCurrency":"UAH",
"currency":"CHF",
"saleRateNB":15.6389750,
"purchaseRateNB":15.6389750,
"saleRate":17.0000000,
"purchaseRate":15.5000000
},
{
"baseCurrency":"UAH",
"currency":"RUB",
"saleRateNB":0.3052700,
"purchaseRateNB":0.3052700,
"saleRate":0.3200000,
"purchaseRate":0.2800000
},
{
"baseCurrency":"UAH",
"currency":"GBP",
"saleRateNB":23.6324910,
"purchaseRateNB":23.6324910,
"saleRate":25.8000000,
"purchaseRate":24.0000000
},
{
"baseCurrency":"UAH",
"currency":"USD",
"saleRateNB":15.0564130,
"purchaseRateNB":15.0564130,
"saleRate":15.7000000,
"purchaseRate":15.3500000
},
{
"baseCurrency":"UAH",
"currency":"BYR",
"saleRateNB":0.0013900,
"purchaseRateNB":0.0013900
},
{
"baseCurrency":"UAH",
"currency":"EUR",
"saleRateNB":18.7949200,
"purchaseRateNB":18.7949200,
"saleRate":20.0000000,
"purchaseRate":19.2000000
},
{
"baseCurrency":"UAH",
"currency":"GEL",
"saleRateNB":8.1500890,
"purchaseRateNB":8.1500890
},
{
"baseCurrency":"UAH",
"currency":"PLZ",
"saleRateNB":4.4922010,
"purchaseRateNB":4.4922010,
"saleRate":5.0000000,
"purchaseRate":4.2000000
}
]
}
Еще код, с помощью которого я получаю информацию с сервера:
public class HttpUtil {
public static String sendRequest(String url, Map<String, String> headers, String request) {
String result = null;
HttpURLConnection urlConnection = null;
try {
URL requestUrl = new URL(url);
urlConnection = (HttpURLConnection) requestUrl.openConnection();
urlConnection.setReadTimeout(20000);
urlConnection.setConnectTimeout(20000);
urlConnection.setRequestMethod("GET");
if (request != null) {
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("POST");
DataOutputStream outputStream = new DataOutputStream(urlConnection.getOutputStream());
outputStream.writeBytes(request);
outputStream.flush();
outputStream.close();
}
if (headers != null) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
urlConnection.addRequestProperty(entry.getKey(), entry.getValue());
}
}
int status = urlConnection.getResponseCode();
System.out.println("status code:" + status);
if (status == HttpURLConnection.HTTP_OK) {
result = getStringFromStream(urlConnection.getInputStream());
}
} catch (Exception e) {
System.out.println("sendRequest failed");
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return result;
}
private static String getStringFromStream(InputStream inputStream) throws IOException {
final int BUFFER_SIZE = 4096;
ByteArrayOutputStream resultStream = new ByteArrayOutputStream(BUFFER_SIZE);
byte[] buffer = new byte[BUFFER_SIZE];
int length;
while ((length = inputStream.read(buffer)) != -1) {
resultStream.write(buffer, 0, length);
}
return resultStream.toString("UTF-8");
}
}
public static void main(String[] args) {
String enteredDate = enterDate();
String url = "https://api.privatbank.ua/p24api/exchange_rates?json&date=";
String result = HttpUtil.sendRequest(url, null, null);
System.out.println("Result: " + result);
}
Создаете 2 класса, которые описывают Вашу структуру:
class Basic {
private String date;
private String bank;
private String baseCurrency;
private String baseCurrencyLit;
private List<Inner> exchangeRate;
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getBank() {
return bank;
}
public void setBank(String bank) {
this.bank = bank;
}
public String getBaseCurrency() {
return baseCurrency;
}
public void setBaseCurrency(String baseCurrency) {
this.baseCurrency = baseCurrency;
}
public String getBaseCurrencyLit() {
return baseCurrencyLit;
}
public void setBaseCurrencyLit(String baseCurrencyLit) {
this.baseCurrencyLit = baseCurrencyLit;
}
public List<Inner> getExchangeRate() {
return exchangeRate;
}
public void setExchangeRate(List<Inner> exchangeRate) {
this.exchangeRate = exchangeRate;
}
@Override
public String toString() {
return "Basic{" +
"date='" + date + '\'' +
", bank='" + bank + '\'' +
", baseCurrency='" + baseCurrency + '\'' +
", baseCurrencyLit='" + baseCurrencyLit + '\'' +
", exchangeRate=" + Arrays.toString(exchangeRate.toArray()) +
'}';
}
}
class Inner {
private String baseCurrency;
private String currency;
private String saleRateNB;
private String purchaseRateNB;
private String saleRate;
private String purchaseRate;
public String getBaseCurrency() {
return baseCurrency;
}
public void setBaseCurrency(String baseCurrency) {
this.baseCurrency = baseCurrency;
}
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
public String getSaleRateNB() {
return saleRateNB;
}
public void setSaleRateNB(String saleRateNB) {
this.saleRateNB = saleRateNB;
}
public String getPurchaseRateNB() {
return purchaseRateNB;
}
public void setPurchaseRateNB(String purchaseRateNB) {
this.purchaseRateNB = purchaseRateNB;
}
public String getSaleRate() {
return saleRate;
}
public void setSaleRate(String saleRate) {
this.saleRate = saleRate;
}
public String getPurchaseRate() {
return purchaseRate;
}
public void setPurchaseRate(String purchaseRate) {
this.purchaseRate = purchaseRate;
}
@Override
public String toString() {
return "Inner{" +
"baseCurrency='" + baseCurrency + '\'' +
", currency='" + currency + '\'' +
", saleRateNB='" + saleRateNB + '\'' +
", purchaseRateNB='" + purchaseRateNB + '\'' +
", saleRate='" + saleRate + '\'' +
", purchaseRate='" + purchaseRate + '\'' +
'}';
}
}
Используя Gson:
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.2</version>
</dependency>
, десериализуете Ваш JSON в Ваш объект:
Basic basic = new Gson().fromJson([ваш json], Basic.class);
System.out.println(basic);
Как получить именно доллар, я думаю Вы разберетесь.
Айфон мало держит заряд, разбираемся с проблемой вместе с AppLab
Перевод документов на английский язык: Важность и ключевые аспекты
Пытаюсь парсить две таблицы одна в файлеxls вторая в
Я использую spring + jpa + hibernate и мне нужно чтобы у объекта родителя (пользователь) было много потомков (заметок), следовательно я должен использовать...
В каждом tableRow находится 2 TextViewКак можно сделать промежуток между самым длинным первым TextView и вторым TextView
Хотел сделать Ридер книжек с форматом fb2 на планшет с четвёртым андроидом, и упёрся в проблему: а как прочитать этот формат? Можете подсказать...