0

I'm new with JSON and my question might be not very hard, but I can not find the way to deal with my purpose. I'm trying to develop the code so that I can manage some JSON content. In my case the JSON info is:

{"posts":[{"id":1a00b,"name":"Michael Thomson","info":"he is crazy"},
{"id":18,"name":"Jason Williams","info":"he is tall"}]}

Now, I'd like to get the strings from each JSON object (using Java). That's the code I have developed:

HttpResponse response = httpclient.execute(httppost);           
String jsonResult = inputStreamToString(response.getEntity().getContent()).toString();                      
JSONArray jsonArray = jsonResult.getJSONArray("posts");

for (int i = 0; i < jsonArray.length(); i++) 
{
     JSONObject childJSONObject = jsonArray.getJSONObject(i);
     String id = childJSONObject.getString("id");
     String name = childJSONObject.getString("name");
     String info = childJSONObject.getString("info");
}

The error seems to be related with the sentence:

JSONArray jsonArray = jsonResult.getJSONArray("posts");

The method getJSONArray(String) is undefined for the type String

Those are the libraries I'm using to deal with

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONArray; 

Thank you very much in advance!

2
  • It says "The method getJSONArray(String) is undefined for the type String" Commented Aug 29, 2013 at 18:21
  • 1
    jsonResult is of type String, but you're treating it like a JSONObject or JSONArray. Wrap the jsonResult in a JSONObject and then get its "posts" property, which will be a JSONArray. Commented Aug 29, 2013 at 18:25

1 Answer 1

2

jsonResult is a String. You need to turn it into a JSONObject first.

JSONObject obj = new JSONObject(jsonResult);
JSONArray jsonArray = obj.getJSONArray("posts");
Sign up to request clarification or add additional context in comments.

Comments

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.