1

我收到此错误,似乎无法找到答案。我在谷歌上找到的所有东西都指向我的 php,但似乎没有什么能解决它。JsonParser 类适用于我的注册和登录页面。

错误是

Error parsing data org.json.JSONException: Value <br of type java.lang.String cannot be
converted to JSONArray

Json 解析器类

  public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }


    public JSONObject getJSONFromUrl(final String url) {

        // Making HTTP request
        try {
            // Construct the client and the HTTP request.
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            // Execute the POST request and store the response locally.
            HttpResponse httpResponse = httpClient.execute(httpPost);
            // Extract data from the response.
            HttpEntity httpEntity = httpResponse.getEntity();
            // Open an inputStream with the data content.
            is = httpEntity.getContent();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            // Create a BufferedReader to parse through the inputStream.
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            // Declare a string builder to help with the parsing.
            StringBuilder sb = new StringBuilder();
            // Declare a string to store the JSON object data in string form.
            String line = null;

            // Build the string until null.
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }

            // Close the input stream.
            is.close();
            // Convert the string builder data to an actual string.
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // Try to parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // Return the JSON Object.
        return jObj;

    }


    // function get json from url
    // by making HTTP POST or GET method
    public JSONObject makeHttpRequest(String url, String method,
            List<NameValuePair> params) {

        // Making HTTP request
        try {

            // check for request method
            if(method == "POST"){
                // request method is POST
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params));

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();

            }else if(method == "GET"){
                // request method is GET
                DefaultHttpClient httpClient = new DefaultHttpClient();
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;
                HttpGet httpGet = new HttpGet(url);

                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
            }           

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        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();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}



getLocalBus.class


import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

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


public class GetLocalBus extends Activity {

    private ProgressDialog pDialog;

    //gets JSONParser class
    JSONParser jsonParser = new JSONParser();

   TextView txt;

   double busLat;
   double busLng;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.get_local);


    txt= (TextView) findViewById(R.id.TextView5);
    pDialog = new ProgressDialog(GetLocalBus.this);




    txt.setText("Connecting..."); 
    new readData().execute();

}
public static final String KEY_121 = "http://getData.php"; 

class readData extends AsyncTask<String, String, String> {


    boolean failure = false;

   @Override
   protected void onPreExecute() {
       super.onPreExecute();

       pDialog.setMessage("Getting Places...");
       pDialog.setIndeterminate(false);
       pDialog.setCancelable(true);
       pDialog.show();
   }

    @Override
    protected String doInBackground(String... args) {




       try {

           List<NameValuePair> params = new ArrayList<NameValuePair>();
           params.add(new BasicNameValuePair("lat","37.3324083200000000"));
           params.add(new BasicNameValuePair("lon","122.0304781500000000"));
           params.add(new BasicNameValuePair("dist","90"));

           Log.d("request!", "starting");
           // getting product details by making HTTP request
           JSONObject json = jsonParser.makeHttpRequest(
                   KEY_121, "POST", params);

           busLng = json.optDouble("business_lon",busLng);
           busLat = json.optDouble("business_lat",busLat);


       }
           finally{



           }
    return null;
       } 

   protected void onPostExecute(String file_url) {

           if (pDialog != null) {
               pDialog.dismiss();
               pDialog = null;
           }

           txt.setText(""+busLng+" "+busLat);
   }

}


}

我的 php 文件

<?php


    if(isset($_GET['lat']) && isset($_GET['lon'])&& isset($_GET['dist'])){


        $db = new mysqli("myDatabaseUrl","username","password","DBname",0,"");

        $lat = $_GET['lat'];
        $lon = $_GET['lon'];
        $dist = $_GET['dist'];


        $search_sql = "SELECT business_id, business_lat, business_lon, ( 3959 * acos( cos( radians(37) ) * cos( radians( " . $lat . " ) ) * cos( radians( " . $lon . " ) - radians(-122) ) + sin( radians(37) ) * sin( radians( " . $lat . " ) ) ) ) AS distance 
                        FROM myTable HAVING distance < " . $dist . " ORDER BY distance LIMIT 1 , 20";

        $search_results = $db->query($search_sql);

        if($search_results->num_rows){ 

            while ($search_results->fetch_assoc()){
                //array the the business data 
                $return_data[] = $search_results->fetch_array();
            }//end while

        }else{
            $return_data[] = array(); 
        }//end if


    }else{
        $return_data[] = array();
    }

    $bd_json = json_encode($return_data);

    $db->close();

    echo $bd_json;



?>

我用浏览器查看了源代码,除了 Json 什么都没有看到。这是输出。

[{"0":"3","business_id":"3","1":"37.393885","business_lat":"37.393885","2":"-122.078916","business_lon":"-122.078916","3":"23.0298400562551","distance":"23.0298400562551"},{"0":"5","business_id":"5","1":"37.394011","business_lat":"37.394011","2":"-122.095528","business_lon":"-122.095528","3":"23.0298400562551","distance":"23.0298400562551"},{"0":"7","business_id":"7","1":"37.390038","business_lat":"37.390038","2":"-122.042034","business_lon":"-122.042034","3":"23.0298400562551","distance":"23.0298400562551"},{"0":"9","business_id":"9","1":"32.723831","business_lat":"32.723831","2":"-117.168326","business_lon":"-117.168326","3":"23.0298400562551","distance":"23.0298400562551"},{"0":"11","business_id":"11","1":"47.557704","business_lat":"47.557704","2":"-122.284985","business_lon":"-122.284985","3":"23.0298400562551","distance":"23.0298400562551"},{"0":"13","business_id":"13","1":"47.614005","business_lat":"47.614005","2":"-122.313985","business_lon":"-122.313985","3":"23.0298400562551","distance":"23.0298400562551"},{"0":"15","business_id":"15","1":"47.672670","business_lat":"47.672670","2":"-122.354092","business_lon":"-122.354092","3":"23.0298400562551","distance":"23.0298400562551"},{"0":"17","business_id":"17","1":"47.618314","business_lat":"47.618314","2":"-122.347998","business_lon":"-122.347998","3":"23.0298400562551","distance":"23.0298400562551"},{"0":"19","business_id":"19","1":"41.248662","business_lat":"41.248662","2":"-96.098760","business_lon":"-96.098760","3":"23.0298400562551","distance":"23.0298400562551"},{"0":"21","business_id":"21","1":"41.273084","business_lat":"41.273084","2":"-95.987816","business_lon":"-95.987816","3":"23.0298400562551","distance":"23.0298400562551"}]

编辑

 try {

           double lat1 = 37.3324083200000000;
           String lat = Double.toString(lat1);

           double lon1 = -122.0304781500000000;
           String lon = Double.toString(lon1);

           double dist1 = 25;
           String dist = Double.toString(dist1);

           List<NameValuePair> params = new ArrayList<NameValuePair>();
           params.add(new BasicNameValuePair("lat",lat));
           params.add(new BasicNameValuePair("lon",lon));
           params.add(new BasicNameValuePair("dist",dist));




 LOGIN_URL, "GET", params);

新错误

08-07 00:24:09.567: E/JSON Parser(9658): Error parsing data org.json.JSONException: Value [{"3":"23.0298400562551","2":"-122.078916","distance":"23.0298400562551","business_lon":"-122.078916","1":"37.393885","0":"3","business_lat":"37.393885","business_id":"3"},{"3":"23.0298400562551","2":"-122.095528","distance":"23.0298400562551","business_lon":"-122.095528","1":"37.394011","0":"5","business_lat":"37.394011","business_id":"5"},{"3":"23.0298400562551","2":"-122.042034","distance":"23.0298400562551","business_lon":"-122.042034","1":"37.390038","0":"7","business_lat":"37.390038","business_id":"7"},{"3":"23.0298400562551","2":"-117.168326","distance":"23.0298400562551","business_lon":"-117.168326","1":"32.723831","0":"9","business_lat":"32.723831","business_id":"9"},{"3":"23.0298400562551","2":"-122.284985","distance":"23.0298400562551","business_lon":"-122.284985","1":"47.557704","0":"11","business_lat":"47.557704","business_id":"11"},{"3":"23.0298400562551","2":"-122.313985","distance":"23.0298400562551","business_lon":"-122.313985","1":"47.614005","0":"13","business_lat":"47.614005","business_id":"13"},{"3":"23.0298400562551","2":"-122.354092","distance":"23.0298400562551","business_lon":"-122.354092","1":"47.672670","0":"15","business_lat":"47.672670","business_id":"15"},{"3":"23.0298400562551","2":"-122.347998","distance":"23.0298400562551","business_lon":"-122.347998","1":"47.618314","0":"17","business_lat":"47.618314","business_id":"17"},{"3":"23.0298400562551","2":"-96.098760","distance":"23.0298400562551","business_lon":"-96.098760","1":"41.248662","0":"19","business_lat":"41.248662","business_id":"19"},{"3":"23.0298400562551","2":"-95.987816","distance":"23.0298400562551","business_lon":"-95.987816","1":"41.273084","0":"21","business_lat":"41.273084","business_id":"21"}] of type org.json.JSONArray cannot be converted to JSONObject

需要更改 PHP 端

$db = new mysqli("myDatabaseUrl","username","password","username",0,"");

应该

$db = new mysqli("myDatabaseUrl","username","password","Your_dbname");

您收到此错误是因为 php 在您的 json 输出之前生成错误。""如果您不在非标准端口上运行 mysql,则端口和套接字不能为 0,最好不要管它们。

mysqli构造函数参考http://php.net/manual/en/mysqli.construct.php

mysqli::__construct() ([ string $host = ini_get("mysqli.default_host") [, string $username = ini_get("mysqli.default_user") [, string $passwd = ini_get("mysqli.default_pw") [, string $dbname = "" [, int $port = ini_get("mysqli.default_port") [, string $socket = ini_get("mysqli.default_socket") ]]]]]])

还要检查您发送到 php 的 ULR 格式是否正确。您可以在块之前使用以下命令回显请求的 URL if,脚本将仅返回 URL。

die($_SERVER["REQUEST_URI"]);

Java 端需要的更改

PHP 代码正在发送 JSONObject 的 JSONArray,尝试转换为 json 数组。

 JSONArray jArr = new JSONArray(json);.
4

1 回答 1

1

需要更改 PHP 端

$db = new mysqli("myDatabaseUrl","username","password","username",0,"");

应该

$db = new mysqli("myDatabaseUrl","username","password","Your_dbname");

您收到此错误是因为 php 在您的 json 输出之前生成错误。""如果您不在非标准端口上运行 mysql,则端口和套接字不能为 0,最好不要管它们。

mysqli构造函数参考http://php.net/manual/en/mysqli.construct.php

mysqli::__construct() ([ string $host = ini_get("mysqli.default_host") [, string $username = ini_get("mysqli.default_user") [, string $passwd = ini_get("mysqli.default_pw") [, string $dbname = "" [, int $port = ini_get("mysqli.default_port") [, string $socket = ini_get("mysqli.default_socket") ]]]]]])

还要检查您发送到 php 的 ULR 格式是否正确。您可以在块之前使用以下命令回显请求的 URL if,脚本将仅返回 URL。

die($_SERVER["REQUEST_URI"]);

Java 端需要的更改

PHP 代码正在发送 JSONObject 的 JSONArray,尝试转换为 json 数组。

 JSONArray jArr = new JSONArray(json);.
于 2013-07-30T07:40:54.497 回答