0

Could you please advise me how to parse JSON reply. I'm getting currencies from https://api.privatbank.ua/p24api/pubinfo?json&exchange&coursid=12

public class JavaCurrencyConversion {
public static void getCurrency () throws Exception {
    URL url = new URL("https://api.privatbank.ua/p24api/pubinfo?json&exchange&coursid=12");
    URLConnection connection = url.openConnection();
    BufferedReader in = new BufferedReader(
            new InputStreamReader(
                    connection.getInputStream()));
    String jsonObject = "";
    String line;
    while ((line = in.readLine()) != null)
        jsonObject += line;

    in.close();

How to get buy and sell values for ccy "USD" and "EUR" ?

Bohdan
  • 115
  • 1
  • 3

2 Answers2

2

There are several libraries you can use which will make your life simpler. For example, you can use minimal-json

JsonObject jsonObject = JsonObject.readFrom(new InputStreamReader(inputStream, StandardCharsets.UTF_8));

Or you can use Google Gson

JsonObject jsonObject = new Gson().fromJson(jsonString, JsonObject.class)
samczsun
  • 1,014
  • 6
  • 16
1

The JSON returned by the specified URL represents a JSONArray containing JSONObjects. You will need to traverse the array looking for the JSONObjects that have a ccy attribute set to 'USD' or 'EUR'. Then you simply use the buy or sale attributes.

Jason
  • 11,744
  • 3
  • 42
  • 46