JSONException:java.lang.String类型的值连接无法转换为JSONObject


JSONException: Value connect of type java.lang.String cannot be converted to JSONObject

从localhost:获取数据时出现此错误

分析数据org.json.JSONException时出错:类型为的值连接java.lang.String无法转换为JSONObject

尝试在空对象引用querysearch.java 上调用虚拟方法"java.lang.String org.json.JSONObject.toString()"

JSONArray products = null;
InputStream is;
ProgressDialog pDialog;
public static String fstation="123" ,tstation="Halol";
private static String url_all_products ="http://192.168.163.1/demott/test2.php";
public static String product;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        pDialog = new ProgressDialog(this);


        new GetServices().execute();


        }
class GetServices extends AsyncTask<String, String, String> {
    /**
     * Before starting background thread
     * Show Progress Bar Dialog
     * */
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog.setMessage("Getting Services. Please wait....");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }
    /**
     * Downloading file in background thread
     * */
    protected String doInBackground(String... f_url) {
        try {
            ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("f_station",fstation));

            // getting JSON string from URL
            JSONObject json = JSONParser.makeHttpRequest(url_all_products, "GET", nameValuePairs);
            Log.d("one", "Stagge 3");// Check your log cat for JSON reponse
            Log.d("All Products: ", json.toString());
          // n.toString();
        }
        catch (Exception e) {
            Log.e("Error: ", e.getMessage());
        }
        return null;
    }
    /**
     * After completing background task
     * Dismiss the progress dialog
     * **/
    @Override
    protected void onPostExecute(String file_url) {
        // dismiss the dialog after the file was downloade
        pDialog.dismiss();

    }
}

JSONParser.java

public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public static  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;
}
}

test2.php

<?php
$conn = mysqli_connect("localhost","root","");
if($conn)
{
    echo 'connect to server';
    $select_db=mysqli_select_db($conn,"ttdb");
    if($select_db)
    {
        echo 'connect with databse';
    }
    else
    {
        echo 'Error in connceting database';
    }
}
else
{
    echo 'error in connection';
}
$fromStation=$_REQUEST["f_station"];
    $qry="select * from bus_schedule where Bus_No='".$fromStation."'";
    $a= mysqli_query($conn,$qry);
    if(mysqli_num_rows($a))
    {
        while($result=mysqli_fetch_assoc($a))
        {
            $arr=array();
            $arr['bus_root']=$result['bus_root'];
            $arr['From_stationCode']=$result['From_stationCode'];
            $arr['To_stationCode']=$result['To_stationCode'];
            $arr['Depature_time']=$result['Depature_time'];
            $arr['Arrival_Time']=$result['Arrival_Time'];
        echo json_encode($arr);
    }
}
else
{
    echo 'No result found';
}
?>

php输出连接到服务器使用databse{"bus_root":"1","From_stationCode":"10","Arrival_time":"11"}"Depature_time":"10","Arrival_time":"11"}

像这样更改数组

<?php
$conn = mysqli_connect("localhost","root","");
if($conn)
{
    echo 'connect to server';
    $select_db=mysqli_select_db($conn,"ttdb");
    if($select_db)
    {
        echo 'connect with databse';
    }
    else
    {
        echo 'Error in connceting database';
    }
}
else
{
    echo 'error in connection';
}
$fromStation=$_REQUEST["f_station"];
    $qry="select * from bus_schedule where Bus_No='".$fromStation."'";
    $a= mysqli_query($conn,$qry);
    if(mysqli_num_rows($a))
    {
        while($result=mysqli_fetch_assoc($a))
        {
              $arr = array(
             'bus_root' =$result['bus_root'],
            'From_stationCode'=$result['From_stationCode'],
            'To_stationCode'=$result['To_stationCode'],
            'Depature_time'=$result['Depature_time'],
             'Arrival_Time'=$result['Arrival_Time']);

    }
 header('Content-type: application/json');
 echo json_encode($arr);
}
else
{
    echo 'No result found';
}
?>

您需要根据需要的结果修改数组。看看下面的解决方案,它将以json格式记录所有记录。

<?php
$conn = mysqli_connect("localhost","root","");
if($conn)
{
    echo 'connect to server';
    $select_db=mysqli_select_db($conn,"ttdb");
    if($select_db)
    {
        //echo 'connect with databse';
    }
    else
    {
        //echo 'Error in connceting database';
    }
}
else
{
    //echo 'error in connection';
}
$fromStation=$_REQUEST["f_station"];
    $qry="select * from bus_schedule where Bus_No='".$fromStation."'";
    $a= mysqli_query($conn,$qry);
    if(mysqli_num_rows($a))
    {
        $arr=array();
        $i = 0;
        while($result=mysqli_fetch_assoc($a))
        {
            $arr[$i]['bus_root']=$result['bus_root'];
            $arr[$i]['From_stationCode']=$result['From_stationCode'];
            $arr[$i]['To_stationCode']=$result['To_stationCode'];
            $arr[$i]['Depature_time']=$result['Depature_time'];
            $arr[$i]['Arrival_Time']=$result['Arrival_Time'];
            $i++;
        }
        echo json_encode($arr);
    }
    else
    {
        echo 'No result found';
    }
?>

要了解更多关于数组的信息,请查看PHP数组