1

I have a simple issue, unable to tackle it out since 2 days. Being a newbie in Android is what seems grueling at times. But here goes,

A simple JSON file is depicted as below:

"results" : [
{
 "value1" : {
 "sub-value" : {
 "sub-sub-value1" : "This is one value",
 "sub-sub-value2" : "This is one more.."
 }
 },
 "value2" : "http://someURL.com",
 "value3" : "areferencejunkvalue",
 }
],
...<many such result sets>
 "status" : "status_value"
}

The code is as below for parsing this simple JSON file.

try {
JSONArray results = json.getJSONArray("results");
JSONObject value1 = results.getJSONObject("value1");
JSONArray subvalue = locationGeom.getJSONArray("sub-value");
for (int i = 0; i < results.length(); i++) {
 // Gets data for value2,value3
 String value2 = results.getString("value2");
 String value3 = results.getString("value3");
 // Gets data from the sub-sub-value1
 String ssv1 = subvalue.getJSONObject(0).getString("sub-sub-value1").toString();
 // Gets data from the sub-sub-value2
 String ssv2 = subvalue.getJSONObject(0).getString("sub-sub-value2").toString();
 }
 } catch (JSONException e1) {
Log.e("E", "Issue is here..");
e1.printStackTrace();
}

Now the issue is, the following:

05-06 23:39:07.846: W/System.err(378): org.json.JSONException: Value [JSONObject parsed] at results of type org.json.JSONArray cannot be converted to JSONObject

Can anybody tell me where am I going wrong here? Help is sincerely appreciated.

asked May 7, 2012 at 0:00
1
  • the builtin android json api is difficult, tricky and slow, try using gson, javacodegeeks.com/2011/01/… Commented May 7, 2012 at 0:04

1 Answer 1

2

sub-value is not an array, but an object, e.g.:

JSONArray results = json.getJSONArray("results");
JSONObject value1 = results.getJSONObject(0).getJSONObject("value1");
JSONObject subvalue = locationGeom.getJSONObject("sub-value");

The basic extraction rules are pretty simple:

from \ get | JSONObject | JSONArray
------------+---------------------------------+--------------------------------
JSONObject | jobj.getJSONObject(String key); | jobj.getJSONArray(String key);
JSONArray | jobj.getJSONObject(int index); | jobj.getJSONArray(int index);

Please also refer to:

answered May 7, 2012 at 0:03
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, Sir! Can you explain how to get my values in 'sub-sub-value' object also? Appreciate your timely help!

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.