0

I'm trying to get the value for the key 'GBP' in the following link: https://api.fixer.io/latest

I've managed to connect to the API successfully and I'm able to cycle through the keys until I get "rates". Inside rates though, I don't know how I cycle through all the currencies until I find 'GBP'.

Note: I'm paring the Json - I'm struggling to parse a Json object that has a Json within it. It's different to the duplicates you've referenced.

My code so far looks like this:

String urlStr = "https://api.fixer.io/latest";

AsyncTask.execute(new Runnable() {
                @Override
                public void run() {
                    // Create URL
                    URL url = null;
                    try {
                        url = new URL(urlStr);
                    } catch (MalformedURLException e) {
                        e.printStackTrace();
                    }

                    // Create connection
                    try {
                        HttpURLConnection myConnection =
                                (HttpURLConnection) url.openConnection();

                        if (myConnection.getResponseCode() == 200) {
                            InputStream responseBody = myConnection.getInputStream();
                            InputStreamReader responseBodyReader =
                                    new InputStreamReader(responseBody, "UTF-8");
                            JsonReader jsonReader = new JsonReader(responseBodyReader);

                            jsonReader.beginObject(); // Start processing the JSON object
                            while (jsonReader.hasNext()) { // Loop through all keys
                                String key = jsonReader.nextName(); // Fetch the next key
                                if (key.equals("rates")) { // Check if desired key
                                    // Fetch the value as a String
                                    String value = jsonReader.nextString();

                                    //currentCurrency = value;

                                    break; // Break out of the loop
                                } else {
                                    jsonReader.skipValue(); // Skip values of other keys
                                }
                            }

                        } else {
                            // Error handling code goes here
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
JamMan9
  • 706
  • 2
  • 9
  • 22

4 Answers4

1

Try this

JSONObject jsonObject = new JSONObject(" your json response ");


    Iterator iteratorObj = jsonObject.keys();
    while (iteratorObj.hasNext())
    {
        String JsonObjRates = (String)iteratorObj.next();

        if (JsonObjRates.equals("rates")) {

            JSONObject jo_rates = jsonObject.getJSONObject(JsonObjRates);

            Iterator<String> keys = jo_rates.keys();
            while (keys.hasNext())
            {
                String key = keys.next();
                String value = jo_rates.getString(key);
                Log.i("RATES key", key);
                Log.i("RATES value", value);

                if(key.equals("GBP"))
                {
                        Log.i("GBP RATES key", key);
                        Log.i("GBP RATES value", value);
                }
            }

        }

    }

Output

enter image description here

Ratilal Chopda
  • 4,162
  • 4
  • 18
  • 31
  • @Jamles please check my ans with Output. – Ratilal Chopda Dec 14 '17 at 13:45
  • This looks great. I haven't got it working yet as I need to create a JSONObject and im not doing that above. I'll change what I have and use your solution as it doesn't require any additional dependencies. Thankyou – JamMan9 Dec 14 '17 at 14:07
0

Instead of Using manual parsing used below things.

Please Use RoboPojo Generator into Android Studio it will helps you to create model class for you and directly setData to your model class.

if you are using Gson to setData.

Below ilink is helping to you :

https://github.com/robohorse/RoboPOJOGenerator

hope this helps you.

Jyubin Patel
  • 1,373
  • 7
  • 17
0

You can use Volleylibrary to make request that url and you will take response. after take response via related url, you can parse it on Android Studio.

dependencies {
    ...
    compile 'com.android.volley:volley:1.1.0'
}

above will be added in dependencies.

below will be added in your Activity(like MainActivity).

 String url ="https://api.fixer.io/latest";



     // Request a string response from the provided URL.
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                    new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                JSONObject resultJSON=new JSONObject(response);
                JSONObject rates=resultJSON.getJSONObject("rates");
                string GPB=rates.getString("GPB");
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                mTextView.setText("That didn't work!");
            }
        });
        // Add the request to the RequestQueue.
        queue.add(stringRequest);

I guess it will work. make feedback whether it works or not.

0

Try this.

You have to loop through jsonobject so first create class for rates.

public Rates readRates(JsonReader reader) throws IOException {
 String country_rate = null;


 reader.beginObject();
 while (reader.hasNext()) {
   String name = reader.nextName();
   if (name.equals("GBP")) {
     country_rate = reader.nextString();
   } else {
     reader.skipValue();
   }
 }
 reader.endObject();
 return new Rates(country_rate);

}

Decalre your class at start of this http method

Rates rate = null;

Replace this Code

if (key.equals("rates")) { // Check if desired key
                                // Fetch the value as a String
                                String value = jsonReader.nextString();

                                //currentCurrency = value;

                                break; // Break out of the loop
                            } else {
                                jsonReader.skipValue(); // Skip values of other keys
                            }

With this

if (key.equals("rates"))
{
   rate = readRates(jsonReader);
   String rate_value = rate.country_rate;
}
else 
{
      jsonReader.skipValue(); // Skip values of other keys
 }

For more details https://developer.android.com/reference/android/util/JsonReader.html

Hope it helps.!

Mohamed Mohaideen AH
  • 2,527
  • 1
  • 16
  • 24