简体   繁体   中英

mySQL to PHP to JSON: String Cannot be Converted to JSONObject

I am trying to get data from a mySQL database using PHP. This is my fist real attempt of getting data remotely & using JSON. The php file is functioning correctly because it outputs in a browser as a JSON string and i valadated it using JSONLint . So, I am not sure what I have wrong here. Any help would be greatly appreciated

This is what LogCat is throwing:

Error parsing data org.json.JSONException: Value <?xml of type java.lang.String cannot be converted to JSONObject
threadid=9: thread exiting with uncaught exception (group=0x401dce20)
FATAL EXCEPTION: Thread-10
java.lang.NullPointerException
at com.andaero.test.JSON.JSONMain$1.run(JSONMain.java:39)
at java.lang.Thread.run(Thread.java:1020)

UPDATE: I removed the echo method from the php file as Mark requested. I think it has to do with "JSONArray a = json.getJSONArray("regulatory"). I also tried everyone else's approach with no prevail.

Here are the classes:

public class JSONfunctions {

    public static JSONObject getJSONfromURL(String url) {
        InputStream is = null;
        String result = "regulatory";
        JSONObject jArray = null;

        // http post
        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(url);
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();

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

        // convert response to string
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            result = sb.toString();
        } catch (Exception e) {
            Log.e("log_tag", "Error converting result " + e.toString());
        }

        try {

            jArray = new JSONObject(result);
        } catch (JSONException e) {
            Log.e("log_tag", "Error parsing data " + e.toString());
        }

        return jArray;
    }
}

The List Activity:

public class JSONMain extends ListActivity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.listview);

        final ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();

        new Thread(new Runnable() {
            public void run() {
                JSONObject json = JSONfunctions
                        .getJSONfromURL("http://192.168.1.34/andaero/regulatory_list_ASC.php");

                try {

                    JSONArray a = json.getJSONArray("regulatory");

                    for (int i = 0; i < a.length(); i++) {
                        HashMap<String, String> map = new HashMap<String, String>();
                        JSONObject e = a.getJSONObject(i);

                        map.put("id", String.valueOf(i));
                        map.put("label", e.getString("label"));
                        map.put("title", e.getString("title"));
                        map.put("caption", e.getString("description"));
                        map.put("dummy", e.getString("gotoURL"));
                        mylist.add(map);
                    }
                } catch (JSONException e) {
                    Log.e("log_tag", "Error parsing data " + e.toString());
                }
            }
        }).start();

        ListAdapter adapter = new SimpleAdapter(this, mylist,
                R.layout.list_item, new String[] { "label", "title", "caption",
                        "dummy" }, new int[] { R.id.label, R.id.listTitle,
                        R.id.caption, R.id.dummy });

        setListAdapter(adapter);

        final ListView lv = getListView();
        lv.setTextFilterEnabled(true);
        lv.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                @SuppressWarnings("unchecked")
                HashMap<String, String> o = (HashMap<String, String>) lv
                        .getItemAtPosition(position);
                Toast.makeText(JSONMain.this,
                        "ID '" + o.get("id") + "' was clicked.",
                        Toast.LENGTH_SHORT).show();

            }
        });
    }
} 

The PHP:

<?php
//MySQL Database Connect
include 'andaerologin.php';

mysql_select_db("andaero");
$sql=mysql_query("select * from regulatory_list");

$output = array();
while($row = mysql_fetch_assoc($sql)) {
    $output['regulatory'][] = $row;
}

exit (json_encode($output));

mysql_close();
?>

Try changing your PHP to this:

$output = new stdClass();
$output->regulatory = array();
while($row = mysql_fetch_assoc($sql)) {
    $output->regulatory[] = $row;
}

header('Content-type: application/json');
echo (json_encode($output));

Try changing your PHP script to this:

<?php

  // Hide errors to prevent data corruption
  ini_set('display_errors', 0);

  // For debugging, uncomment these lines to show errors
  //ini_set('display_errors', 0);
  //error_reporting(E_ALL);

  //MySQL Database Connect
  require 'andaerologin.php';

  if (!mysql_select_db("andaero")) {
    // Use trigger_error() so you can find out in the server logs if something
    // goes wrong
    trigger_error('Unable to select MySQL database');
    header('HTTP/1.1 500 Internal Server Error');
    exit;
  }

  $query = "SELECT *
            FROM regulatory_list";
  if (!$result = mysql_query($query)) {
    trigger_error('MySQL error: '.mysql_error());
    header('HTTP/1.1 500 Internal Server Error');
    exit;
  }

  if (!mysql_num_rows($query)) {
    trigger_error('MySQL returned no results');
    header('HTTP/1.1 500 Internal Server Error');
    exit;
  }

  // Build an array of the results
  $output = array();
  while ($row = mysql_fetch_assoc($result)) {
    $output[] = $row;
  }

  // Send the results back as JSON
  exit(json_encode($output));

  // Closing the database connection happens implicitly at the end of the
  // script. Also, you don't need to have a closing PHP tag at the end of the
  // file and omitting it is a good habit to get into as it can avoid problems

In your PHP code, change

json_encode($output)

to

json_encode($output, JSON_FORCE_OBJECT)

The JSON_FORCE_OBJECT option requires PHP version >= 5.3.0

Your problem seems to be at jArray = new JSONObject(result);

I don't know what the JSONObject constructor expects, but I know you are sending a JSON array to it, not an object .

Do you really need all those fields in the table?

I once did the same, SELECT * FROM table, and json_encode() all the results. jQuery seemed to have a problem reading the data even though the JSON result looks perfectly fine.

So I tried to limit the data and send only the required fields to the browser by SELECT field1, field2 FROM table, instead of all the fields.

Then everything worked fine. I could only suspect that there's a limit to the amount of JSON data jQuery can parse.

I know you aren't using jQuery but I'm just leaving my experience here just in case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM