1

I tried to get an answer from server and conver it to JSONObject. At Now I have this code

private JSONObject sendData(ArrayList<NameValuePair> data, String actionname)

{

    // 1) Connect via HTTP. 2) Encode data. 3) Send data.
    try

    {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new      
        HttpPost(actionname);
        httppost.setEntity(new UrlEncodedFormEntity(data));
        HttpResponse response = httpclient.execute(httppost);
    //   Log.i("postData", response.getStatusLine().toString());
        InputStream is = response.getEntity().getContent();
        String result = convertStreamToString(is);

     //   JSONArray jArr = new JSONArray (result);
       // int eventID = jArr.getJSONObject(0).getInt("eventID");

        JSONObject jObject = new JSONObject(result);
        return jObject;

    }
    catch(Exception e)
    {
        Log.e("log_tag", "Error:  "+e.toString());
    }

    return null;  

}

in result string variable I have this

{"status":{"code":404,"text":"Not Found"},"content":"User authentication failure"}

But on the string of code JSONObject jObject = new JSONObject(result); - It go to the return null; =(( I tried to create JSONArray but it return me an extention that I can create JSONARRAY from JSONObject.

1
  • 1
    you must have error above line JSONObject jObject = new JSONObject(result); jsut print the result in log and check.......... Commented Jun 12, 2012 at 11:58

2 Answers 2

1

From result you can create JSONArray as follows:

JSONArray finalResult = new JSONArray(new JSONTokener(result));

Once you have JSONArray, you can loop through to get the details, something like below:

for (int i = 0; i < finalResult.length(); i++) {
    JSONObject message = finalResult.getJSONObject(i);
    String content= message.getString("content");
    ...
    ...
}
Sign up to request clarification or add additional context in comments.

1 Comment

org.json.JSONException: Value {"content":" ","status":{"text":"Not Found","code":404}} of type org.json.JSONObject cannot be converted to JSONArray - took this
0

I solved the problem, but I don't understand why it so. May be I am not so good in OOP. So I create JSONObject jObject as a property of class JSONHandler, that have sendData method. And it became work. I will be happy if somebode explain me why it so.

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.