【问题标题】:JSONException: Value connect of type java.lang.String cannot be converted to JSONObjectJSONException:java.lang.String 类型的值连接无法转换为 JSONObject
【发布时间】:2016-01-11 06:11:26
【问题描述】:

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

解析数据时出错 org.json.JSONException: Value connect of type 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 输出 连接到服务器连接数据库{"bus_root":"1","From_stationCode":"1","To_stationCode":"2","Depature_time":"0","Arrival_Time":"0"}{"bus_root" :"1","From_stationCode":"1","To_stationCode":"4","Depature_time":"10","Arrival_Time":"11"}{"bus_root":"1","From_stationCode": "1","To_stationCode":"3","Depature_time":"10","Arrival_Time":"11"}

【问题讨论】:

  • 检查php代码是否会输出json?
  • 也发布您的回复
  • @sasikumar 是的,它提供了输出
  • 将`echo json_encode($arr);`移出while循环
  • @VivekMishra php 输出??

标签: php android json


【解决方案1】:

像这样改变你的数组

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

【讨论】:

    【解决方案2】:

    你需要根据想要的结果修改数组。看看下面的解决方案,它将以 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 Arrays

    【讨论】:

    • 从代码中删除所有其他回显以获得纯json输出
    • 谢谢..它正在工作,但现在我得到 json 对象的错误 解析数据时出错 org.json.JSONException: Value [{"bus_root":"1","From_stationCode":"1", "To_stationCode":"2","Depature_time":"0","Arrival_Time":"0"},{"bus_root":"1","From_stationCode":"1","To_stationCode":"4", "Depature_time":"10","Arrival_Time":"11"},{"bus_root":"1","From_stationCode":"1","To_stationCode":"3","Depature_time":"10", org.json.JSONArray 类型的 "Arrival_Time":"11"}] 无法转换为 JSONObject
    • @Nilay 删除了所有其他回声,例如 echo 'connect to server';等
    • @Nilay 我不知道java语言..我只能用php帮助你:(
    猜你喜欢
    • 2012-05-03
    • 1970-01-01
    • 2017-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多