Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Navigate In Json (Java)

I am not familiar with JSON so if I am using wrong terms, sorry for that.

So I have this URL:

 final String PRICE_TRY_URL = "https://api.coindesk.com/v1/bpi/currentprice/try.json";

And it returns something like this:

Formatted JSON Data

{  
   "time":{  },
   "disclaimer":"This data was produced from the CoinDesk Bitcoin Price Index (USD). Non-USD currency data converted using hourly conversion rate from openexchangerates.org",
   "bpi":{  
      "USD":{  
         "code":"USD",
         "rate":"6,911.7500",
         "description":"United States Dollar",
         "rate_float":6911.75
      },
      "TRY":{  
         "code":"TRY",
         "rate":"35,738.0058",
         "description":"Turkish Lira",
         "rate_float":35738.0058
      }
   }
}

All I want to do is reach TRY's rate. I get that data with the code below.

public void doNetworking(){
        AsyncHttpClient client=new AsyncHttpClient();
        client.get(PRICE_TRY_URL, new AsyncHttpResponseHandler() {

                    @Override
                    public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                        Log.d("BitcoinTracker","Succes in doNetworking");
                        // byte[] responseBody can be parsed to a json object.
                        parseJson(responseBody);
                    }

                    @Override
                    public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                        Log.e("BitcoinTracker", "Fail " + error.toString());
                    }
                }
        );

And here is my method :

public void parseJson(byte[] responseBody){
        try {
            JSONObject bitcoinJson  =new JSONObject(new String(responseBody));
            String currency=  bitcoinJson.getString("bpi");
            Log.d("bitcoinmanager",currency);

        } catch (JSONException e) {
            Log.d("BitcoinPrice","BitcoinPriceManager onSucces converting json from byte[] failed.");
            e.printStackTrace();
        }
    }

As you can see above I use this statement :

String currency=  bitcoinJson.getString("bpi");

And with this statement, I can't reach my destination point which is TRY's rate. How can I navigate in JSON formatted text?

NOTE: I add the getting JSON data part to make sure that my question is clear, hope it is not too much.

like image 425
Gilthoniel Avatar asked Dec 02 '25 09:12

Gilthoniel


2 Answers

If you're using Android, no need to use anything external:

JSONObject bitcoinJson = new JSONObject(responseBody);
JSONObject bpi = bitcoinJson.getJSONObject("bpi");
JSONObject tr = bpi.getJSONObject("TRY");
String rate = tr.getString("rate");

Original answer using the org.json.simple library, before question was tagged as Android:

JSONObject bitcoinJson = (JSONObject)new JSONParser().parse(new String(responseBody));
JSONObject bpi = (JSONObject)bitcoinJson.get("bpi");
JSONObject tr = (JSONObject)bpi.get("TRY");
String rate = (String)tr.get("rate");

Note that instead of constructing a string to pass to the JSONParser, it's a bit more efficient just to give it access to the Reader directly.

like image 74
Michael Berry Avatar answered Dec 04 '25 23:12

Michael Berry


You can use this code with Gson library:

client.get(PRICE_TRY_URL, new TextHttpResponseHandler() {

    @Override
    public void onSuccess(int statusCode, Header[] headers, String res) {
            // called when response HTTP status is "200 OK"
            JsonParser jsonParser = new JsonParser();
            JsonObject jsonObject = (JsonObject) jsonParser.parse(responseBodyString);
            JsonObject bpi = jsonObject.get("bpi").getAsJsonObject();
            JsonObject tryObject = bpi.get("TRY").getAsJsonObject();
            String rate = tryObject.get("rate").getAsString();
    }

    @Override
    public void onFailure(int statusCode, Header[] headers, String res, Throwable t) {
        // called when response HTTP status is "4XX" (eg. 401, 403, 404)
    }   
  }
);

There are examples here https://github.com/codepath/android_guides/wiki/Using-Android-Async-Http-Client

like image 39
Ehsan Mashhadi Avatar answered Dec 04 '25 22:12

Ehsan Mashhadi