CBA110
CBA110

Reputation: 1092

Parse JSON URL with Android Volley - JsonObjectRequest

I'm trying to parse a JSON feed at the following URL but I'm not sure how to use the Volley JsonObjectRequest method since I keep getting an error. I believe it's because I'm not traversing through the JSON object tree correctly but I'm not sure how I would do this given the JSON feed presented above. Below is my method code.

// json object response url - Yahoo Finance
private String urlJsonObjEx = "http://finance.yahoo.com/webservice/v1/symbols/allcurrencies/quote?format=json";

private void makeJsonObjectRequest() {

    showpDialog();

    JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
            urlJsonObjEx, null, new Response.Listener<JSONObject>() {

        @Override
        public void onResponse(JSONObject response) {
            Log.d(TAG, response.toString());

            try {
                // Parsing json object response
                // response will be a json object

                String name = response.getString("name");
                String price = response.getString("price");
                String symbol = response.getString("symbol");
                String timeStamp = response.getString("ts");

                jsonResponse = "";
                jsonResponse += "Name: " + name + "\n\n";
                jsonResponse += "Price: " + price + "\n\n";
                jsonResponse += "Symbol: " + symbol + "\n\n";
                jsonResponse += "Time Stamp: " + ts + "\n\n";

                txtResponse.setText(jsonResponse);

            } catch (JSONException e) {
                e.printStackTrace();
                Toast.makeText(getApplicationContext(),
                        "Error: " + e.getMessage(),
                        Toast.LENGTH_LONG).show();
            }
            hidepDialog();
        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            VolleyLog.d(TAG, "Error: " + error.getMessage());
            Toast.makeText(getApplicationContext(),
                    error.getMessage(), Toast.LENGTH_SHORT).show();
            // hide the progress dialog
            hidepDialog();
        }
    });

    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(jsonObjReq);
}

I keep getting the following error:

Error: No value for name

I believe this is simply due to the fact that name is the first object in the list and my method implementation just fails to parse through. I believe I should be using something similar to the code below:

JSONObject name = response.getJSONObject("name");

But I'm not sure. How to implement this method?

Below is the LogCat:

    07-06 16:28:04.636: W/System.err(14288): org.json.JSONException: No value for name
07-06 16:28:04.637: W/System.err(14288):    at org.json.JSONObject.get(JSONObject.java:389)
07-06 16:28:04.637: W/System.err(14288):    at org.json.JSONObject.getString(JSONObject.java:550)
07-06 16:28:04.637: W/System.err(14288):    at uk.co.codepix.calculator.ui.activities.CurrencyConverterCalc$3.onResponse(CurrencyConverterCalc.java:271)
07-06 16:28:04.637: W/System.err(14288):    at uk.co.codepix.calculator.ui.activities.CurrencyConverterCalc$3.onResponse(CurrencyConverterCalc.java:254)
07-06 16:28:04.637: W/System.err(14288):    at com.android.volley.toolbox.JsonRequest.deliverResponse(JsonRequest.java:65)
07-06 16:28:04.637: W/System.err(14288):    at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
07-06 16:28:04.637: W/System.err(14288):    at android.os.Handler.handleCallback(Handler.java:739)
07-06 16:28:04.637: W/System.err(14288):    at android.os.Handler.dispatchMessage(Handler.java:95)
07-06 16:28:04.637: W/System.err(14288):    at android.os.Looper.loop(Looper.java:135)
07-06 16:28:04.637: W/System.err(14288):    at android.app.ActivityThread.main(ActivityThread.java:5254)
07-06 16:28:04.637: W/System.err(14288):    at java.lang.reflect.Method.invoke(Native Method)
07-06 16:28:04.637: W/System.err(14288):    at java.lang.reflect.Method.invoke(Method.java:372)
07-06 16:28:04.638: W/System.err(14288):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
07-06 16:28:04.638: W/System.err(14288):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
07-06 16:28:04.653: W/InputMethodManagerService(547): Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy@a3c1cf8 attribute=null, token = android.os.BinderProxy@91d9236
07-06 16:28:05.033: W/ProcessCpuTracker(547): Skipping unknown process pid 15912
07-06 16:28:05.034: W/ProcessCpuTracker(547): Skipping unknown process pid 15915
07-06 16:28:05.036: W/ProcessCpuTracker(547): Skipping unknown process pid 15917
07-06 16:28:05.040: W/ProcessCpuTracker(547): Skipping unknown process pid 15918

Upvotes: 0

Views: 2015

Answers (1)

meda
meda

Reputation: 45490

You are not accessing your data properly

jsonResponse = "";
JSONArray ressources = response.getJSONArray("resources");
for (int i = 0; i < jsonarray.length(); i++) {
    String name = ressources.getJSONObject(i).getJSONObject("resource").getJSONObject("fields").getString("name");
    String price = ressources.getJSONObject(i).getJSONObject("resource").getJSONObject("fields").getString("price");
    String symbol = ressources.getJSONObject(i).getJSONObject("resource").getJSONObject("fields").getString("symbol");
    String timeStamp = ressources.getJSONObject(i).getJSONObject("resource").getJSONObject("fields").getString("ts");


    jsonResponse += "Name: " + name + "\n\n";
    jsonResponse += "Price: " + price + "\n\n";
    jsonResponse += "Symbol: " + symbol + "\n\n";
    jsonResponse += "Time Stamp: " + ts + "\n\n";
}

txtResponse.setText(jsonResponse);

I put it in a loop because it is an array of object.

EDIT:

A little more simplified:

for (int i = 0; i < jsonarray.length(); i++) {

    JSONObject resource = ressources.getJSONObject(i).getJSONObject("resource");
    JSONObject fields = getJSONObject("fields");

    jsonResponse += "Name: " + fields.getString("name") + "\n\n";
    jsonResponse += "Price: " + fields.getString("price") + "\n\n";
    jsonResponse += "Symbol: " + fields.getString("symbol") + "\n\n";
    jsonResponse += "Time Stamp: " + fields.getString("ts") + "\n\n";
}

Upvotes: 4

Related Questions