JamMan9
JamMan9

Reputation: 776

Parsing JSON data from an HTTP connection

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();
                    }
                }
            });

Upvotes: 0

Views: 723

Answers (4)

Mohamed Mohaideen AH
Mohamed Mohaideen AH

Reputation: 2545

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.!

Upvotes: 0

Ratilal Chopda
Ratilal Chopda

Reputation: 4220

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

Upvotes: 1

vahitdurmus
vahitdurmus

Reputation: 39

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.

Upvotes: 0

Jyubin Patel
Jyubin Patel

Reputation: 1373

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.

Upvotes: 0

Related Questions