Ely Jenkins
Ely Jenkins

Reputation: 1

Pull JSONObject from JSONArray?

I'm trying to pull the "price" object from the "current" array, I have been at it for hours now with no luck, any help is appreciated! :)

try {
            URL url = new URL("http://services.runescape.com/m=itemdb_rs/api/catalogue/detail.json?item=2");
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            try {
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                StringBuilder stringBuilder = new StringBuilder();
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    stringBuilder.append(line).append("\n");
                }
                bufferedReader.close();
                return stringBuilder.toString();
            } finally {
                JSONArray nu1 = jobj.getJSONArray("current");
                JSONObject jobj = nu1.getJSONObject(0);
                String price = jobj.getString("price");
                Toast.makeText(getApplicationContext(), price, Toast.LENGTH_SHORT).show();
            }

        } catch (Exception e) {
            Log.e("ERROR", e.getMessage(), e);
            return null;
        }
    }

    protected void onPostExecute(String response) {

    }
}

}

Upvotes: 0

Views: 38

Answers (1)

saeed soltani
saeed soltani

Reputation: 36

I tried to get response from your URL. here is the response :

{
"item": {
    "icon": "http://services.runescape.com/m=itemdb_rs/1502782993572_obj_sprite.gif?id=2",
    "icon_large": "http://services.runescape.com/m=itemdb_rs/1502782993572_obj_big.gif?id=2",
    "id": 2,
    "type": "Ammo",
    "typeIcon": "http://www.runescape.com/img/categories/Ammo",
    "name": "Cannonball",
    "description": "Ammo for the Dwarf Cannon.",
    "current": {
        "trend": "neutral",
        "price": 339
    },
    "today": {
        "trend": "positive",
        "price": "+1"
    },
    "members": "true",
    "day30": {
        "trend": "positive",
        "change": "+1.0%"
    },
    "day90": {
        "trend": "negative",
        "change": "-11.0%"
    },
    "day180": {
        "trend": "negative",
        "change": "-21.0%"
    }
}
}

there is no array in the response.

Edit:

assume that you store your response in a String named response, you can get price, using the following code:

        JSONObject json = new JSONObject(response);
        JSONObject item = json.getJSONObject("item");
        JSONObject current = item.getJSONObject("current");
        int price = current.getInt("price");

Edit2: use

String response =  stringBuilder.toString();

and then make a JSONObject from 'response' .

Upvotes: 1

Related Questions