java - org.json.JSONObject cannot be converted to JSONArray when receiving JSON code on Android App

641

I am trying to read JSON data from a localhost PHP file. It successfully connects but I get the error

05-27 15:40:24.108: E/log_tag(17146): Error Parsing Data org.json.JSONException: Value {"firstName":"John","lastName":"Doe"} of type org.json.JSONObject cannot be converted to JSONArray

When I open the PHP script in my browser it successfully displays{ "firstName":"John" , "lastName":"Doe" }

package com.example.testexternaldatabase;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.widget.TextView;

public class MainActivity extends Activity {
/** Called when the activity is first created. */

TextView resultView;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.fragment_main);
    StrictMode.enableDefaults(); // STRICT MODE ENABLED
    resultView = (TextView) findViewById(R.id.textView1);

    getData();
}

public void getData() {
    String result = "";
    InputStream isr = null;
    try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://www.mstreetllc.com/Lab.asp"); // YOUR PHP
                                                                    // SCRIPT
                                                                    // ADDRESS
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        isr = entity.getContent();
    } catch (Exception e) {
        Log.e("log_tag", "Error in http connection " + e.toString());
        resultView.setText("Couldnt connect to database");
    }
    // convert response to string
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                isr, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        isr.close();

        result = sb.toString();
    } catch (Exception e) {
        Log.e("log_tag", "Error  converting result " + e.toString());
    }

    // parse json data
    try {

        String s = "";
        JSONArray jArray = new JSONArray(result);
        for (int i = 0; i < jArray.length(); i++) {
            JSONObject json = jArray.getJSONObject(i);
            s = s + "Name : " + json.getString("name") + "\n"
                    + "Email : " + json.getString("email") + "\n\n";
        }

        resultView.setText(s);

    } catch (Exception e) {
        // TODO: handle exception
        Log.e("log_tag", "Error Parsing Data " + e.toString());
    }

}

Any ideas on how I can fix this? Thanks.

185

Answer

Solution:

You're trying to convert what is considered a JSONObject directly into a JSONArray, which is throwing the error you're getting.

A JSONObject would start and and with the brackets { and }, respectively. A JSONArray would start and end with [ and ], respectively, as well as be deliminated by commas, similar to the fields in a JSONObject.

E.g. JSONObject:

{ 
    "firstName":"John", 
    "lastName":"Doe" 
}

E.g JSONArray containing 2 of your original objects inside a JSONObject:

{ 
    "the_name_of_your_json_array": [
         { 
              "firstName":"John", 
              "lastName":"Doe" 
          },
         { 
              "firstName":"John", 
              "lastName":"Doe" 
          }
    ]
}

Now, to fix your code, since you're only receiving a single JSONObject:

    String s = "";
    JSONObject json = new JSONObject(result);
    s = s + "Name : " + json.getString("name") + "\n" + "Email : " + json.getString("email") + "\n\n";

If you're actually returning an array of data (or if that's your intention), it will still be wrapped inside a JSONObject, and would have to be adjusted like so:

    String s = "";
    JSONArray jArray = new JSONObject(result).getJSONArray("the_name_of_your_json_array");
    for (int i = 0; i < jArray.length(); i++) {
        JSONObject json = jArray.getJSONObject(i);
        s = s + "Name : " + json.getString("name") + "\n" + "Email : " + json.getString("email") + "\n\n";
    }

And inside your PHP Script, you would want to encode like so:

json_encode(array('the_name_of_your_json_array' => $your_original_array_of_data)); 

Don't forget to replace the variable names with whatever you're actually using, and hopefully I was descriptive enough without comments.

965

Answer

Solution:

You can do this :

// parse json data
try {

    String s = "";
    JSONObject json = new JSONObject(result);

    s = s + "First Name : " + json.getString("firstName") + "\n"
                + "Last Name : " + json.getString("lastName") + "\n\n";
    resultView.setText(s);

} catch (Exception e) {
    // TODO: handle exception
    Log.e("log_tag", "Error Parsing Data " + e.toString());
}

People are also looking for solutions to the problem: php - Fatal error: Using $this when not in object context but everything looks fine

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.