0

I'm new to JSON. I'm trying to read the String in JSON but it throw me an error.

String strResponse = "{"IndustryList" : [{"industryId" : "1","industryName" : "Bird Nest","industryStatus" : "0","industryDescription" : "Bird nest industry","industryIconFilepath" : "","industryIconFilename" : ""},{"industryId" : "2","industryName" : "Medicine","industryStatus" : "0","industryDescription" : "Medicine Products","industryIconFilepath" : "","industryIconFilename" : ""}]}"

JSONObject json_data = new JSONObject(strResponse);
JSONArray nameArray = json_data.names(); 
JSONArray valArray = json_data.toJSONArray(nameArray);
Log.i(MainActivity.class.getName(),
             "Number of entries " + valArray.length());
for (int i = 0; i < valArray.length(); i++) {
    JSONObject jsonObject = valArray.getJSONObject(i);
    Log.i(MainActivity.class.getName(), jsonObject.getString("text"));
}

Error:

at 0 of type org.json.JSONArray cannot be converted to JSONObject
4
  • 4
    The first line of your code doesn't contain a valid Java String, JSON or not. Commented Aug 7, 2012 at 8:49
  • 1
    Can you be more specific about the JSON framework you use and at which line exactly you ge the exception? Note that the more effort you put into the question the more effort people will put into their answers. Commented Aug 7, 2012 at 8:51
  • actually I get the response from web service. I convert the Object response to string. This is what I get when convert from Object response to String. Commented Aug 7, 2012 at 8:52
  • i get the error at.. JSONObject jsonObject = valArray.getJSONObject(i); Commented Aug 7, 2012 at 8:53

1 Answer 1

1

The problem is that toJSONArray returns array of values. And it has only 1 element - industryList value. Which is array itself. So you need to iterate throw valArray.getJSONArray(0) not through valArray

Sign up to request clarification or add additional context in comments.

5 Comments

do you mean that I need to change my for loop from valArray.length() to valArray.getJSONArray(0)...
Yes. Or you can make this: JSONArray valArray = json_data.toJSONArray(nameArray).getJSONArray(0);
@China_82 Why do you use names to get all keys in json object? Why don't you use names directly, like JSONArray valArray = json_data.getJSONObject('industryList');?
I got Type mismatch: cannot convert from JSONObject to JSONArray when i use JSONArray valArray = json_data.getJSONObject("industryList");
@chinna_82 sorry, getJSONArray("industryList")

Your Answer

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.