【问题标题】:mySQL to PHP to JSON: String Cannot be Converted to JSONObjectmySQL 到 PHP 到 JSON:字符串无法转换为 JSONObject
【发布时间】:2012-02-14 14:31:49
【问题描述】:

我正在尝试使用 PHP 从 mySQL 数据库中获取数据。这是我第一次真正尝试远程获取数据并使用 JSON。 php 文件运行正常,因为它在浏览器中输出为 JSON 字符串,并且我使用 JSONLint 对其进行了验证。所以,我不确定我在这里有什么问题。任何帮助将不胜感激

这就是 LogCat 所抛出的:

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)

更新: 我按照 Mark 的要求从 php 文件中删除了 echo 方法。我认为这与“JSONArray a = json.getJSONArray("regulatory") 有关。我也尝试了其他所有人的方法,但没有占上风。

以下是课程:

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;
    }
}

列表活动:

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();

            }
        });
    }
} 

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();
?>

【问题讨论】:

  • 你相信在json之前输出的“echo 'Connected successfully';”可能与它有关吗?
  • 不是echo 'Connected successfully';破坏了json语法???
  • @Mark Ba​​ker 我将如何检查或更改它?我认为它在浏览器中打印是件好事......?
  • @Andaero 除了你是 JSONObject json = JSONfunctions .getJSONfromURL("10.0.2.2/regulatory_list_ASC.php"); 期待 json 返回,它不期待“json 与一点点纯文本抛出好措施”
  • 完全删除它......它的输出位置无关紧要,它仍然意味着您正在输出“带有一点纯文本的json”并且不正确格式化的json

标签: java php mysql json


【解决方案1】:

尝试将您的 PHP 更改为:

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

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

【讨论】:

    【解决方案2】:

    尝试将您的 PHP 脚本更改为:

    <?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
    

    【讨论】:

    • 有趣,这在浏览器中没有返回任何数据。
    • 查看 Web 服务器的错误日志。另外,请参阅上面有关向浏览器显示错误的编辑。
    【解决方案3】:

    在你的 PHP 代码中,改变

    json_encode($output)
    

    json_encode($output, JSON_FORCE_OBJECT)
    

    JSON_FORCE_OBJECT 选项需要 PHP 版本 >= 5.3.0

    您的问题似乎出在jArray = new JSONObject(result);

    我不知道 JSONObject 构造函数期望什么,但我知道您正在向它发送 JSON array,而不是 object

    【讨论】:

      【解决方案4】:

      您真的需要表格中的所有这些字段吗?

      我曾经做过同样的事情,SELECT * FROM table,然后json_encode()所有的结果。尽管 JSON 结果看起来非常好,但 jQuery 似乎在读取数据时遇到了问题。

      所以我尝试限制数据,只通过 SELECT field1, field2 FROM table 将必填字段发送到浏览器,而不是所有字段。

      然后一切正常。我只能怀疑 jQuery 可以解析的 JSON 数据量是有限的。

      我知道你没有使用 jQuery,但我只是把我的经验留在这里以防万一。

      【讨论】:

      • 感谢您的输入。不幸的是,我确实需要重新调整所有字段(9 行中的 5 列)来填充 txt 字段。 jQuery Rocks - 我在我的应用程序中使用它。
      猜你喜欢
      • 1970-01-01
      • 2021-11-15
      • 2012-05-12
      • 2013-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-02
      相关资源
      最近更新 更多