解析错误!无法解析无法解析stringorg.json.JSONException:Value

时间:2014-03-31 14:28:28

标签: java php android json

我目前正在研究与数据库连接相关的android项目。作为App的一部分,有一种活动可以将数据插入数据库并检索响应是否插入。 Activity正确地将数据插入数据库但是,它触发了JSON解析异常,无法获得响应。 这是我的logcat scrreen:

03-31 09:49:38.196: D/JSON String:(884): Connection Error
03-31 09:49:38.236: D/Parsing Error!(884): Can't parse the stringorg.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
03-31 09:49:38.236: D/Exception!(884): java.lang.NullPointerException
03-31 09:49:38.526: W/InputMethodManagerService(373): Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy@b410d300 attribute=null, token = android.os.BinderProxy@b40b3160

这是我的PHP数据库连接脚本:config.inc.php 我认为这是错误的!!

<?php

    $username = "homeyadmin";
    $password = "8YvUPxCsVHEca2Ru";
    $host = "localhost";
    $dbname = "homey_db";

    //Communicate via UTF8
    $options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');

    try {
        //Is this required??
        // $db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options);
        mysql_connect('localhost','$username','$password') or die("Connection Error");
        mysql_select_db($dbname) or die("no db found");

    } catch(PDOException $ex) {
        die("Failed to connect to Database!" +$ex.toString());
    }

    /*header('Content-Type: text/html; charset=utf-8');
    session_start();*/
?>

最后是JSONParser类:

        public JSONObject makeHttpRequest(String url, String method, List<NameValuePair> params) {

            try {

                if (method == "POST") {

                    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();
                    Log.d("Input Stream:", is.toString());

                } else if (method == "GET") {

                    DefaultHttpClient httpClient = new DefaultHttpClient();
                    String paramString = URLEncodedUtils.format(params, "utf8");
                    url += "?" +paramString;
                    HttpGet httpGet = new HttpGet(url);

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

                } 
            } catch (Exception ex) {
                ex.toString();
            }

            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();
                Log.d("JSON String:", json);
            } catch (Exception e) {
                Log.d("Buffer Error!", "Can't convert result" +e.toString());
            }

            //Time to parse the string into JSONObject

            try {
                jobj = new JSONObject(json);
            } catch (JSONException ex) {
                Log.d("Parsing Error!", "Can't parse the string" +ex.toString());
            }

            return jobj;        
        }
}

这是我的PHP代码

<?php

require("config.inc.php"); 

    if(!empty($_POST)){

        if (empty($_POST['FNAME']) || empty($_POST['LNAME']) || empty($_POST['EMAIL']) || empty($_POST['PASS'])
        || empty($_POST['HNAME']) || empty($_POST['HPNO']) || empty($_POST['HADD2']) 
        || empty($_POST['HLANDMARK']) || empty($_POST['HNAME'])
        || empty($_POST['HCOUNTRY']) || empty($_POST['HSTATE']) 
        || empty($_POST['HCITY']) || empty($_POST['HPHONE'])) {

            //Creating JSON response
            $response["success"] = 0;
            $response["message"] = "All the fields are required!";

            die(json_encode($response));
        }
        //List OF variables
        $fname = $_POST['FNAME'];
        $lname = $_POST['LNAME'];
        $email = $_POST['EMAIL'];
        $pass = $_POST['PASS'];
        $hname = $_POST["HNAME"];
        $hpno = $_POST["HPNO"];
        $hadd2 = $_POST["HADD2"];
        $hland = $_POST["HLANDMARK"];
        $hcon = $_POST["HCOUNTRY"];
        $hstate = $_POST["HSTATE"];
        $hcity = $_POST["HCITY"];
        $hphone = $_POST["HPHONE"];     

        //If page not died
        $result = mysql_query("SELECT 1 FROM owner_info WHERE owner_email = '$email'");
        $num = mysql_num_rows($result);
        echo $num;
        $i = 0;
        if($num = $i) {
            //JSON Response
            $response["success"] = 0;
            $response["message"] = "Email ID is already in use!";

            die(json_encode($response));
        }
        //If None of these condition followed
        $query = "INSERT INTO
            owner_info (owner_fname, owner_lname, owner_email, owner_pass)
            VALUES('$fname', '$lname', '$email', '$pass')
        ";

        if(mysql_query($query)){
            echo "done";
        }else{
            echo mysql_error();
        }

        $result1 = mysql_query("SELECT owner_id
            FROM owner_info
            WHERE owner_email = '$email'
        ");
        if ($result1) {
            while ($row = mysql_fetch_assoc($result1)) {
                echo $temp_owner_id = $row['owner_id'];
            }
            mysql_query("INSERT INTO
                hostel_info (h_owner_id, h_name, h_plot_no, h_address2, h_landmark, h_country, h_state, h_city, h_contact_no)
                VALUES ('$temp_owner_id', '$hname', '$hpno', '$hadd2', '$hland', '$hcon', '$hstate', '$hcity', '$hphone')
            ");
            $response["success"] = 1;
            $response["message"] = "Data inserted successfully.";
            die(json_encode($response));
        } else {
            $response["success"] = 0;
            $response["message"] = "Database Error!!";
            die(json_encode($response));    
        }

    }

请帮助伙伴!!

1 个答案:

答案 0 :(得分:2)

您获得了无效的JSON,这就是为什么它没有被解析。 只需添加此代码即可查看从服务器获取的内容:

    try {
            jobj = new JSONObject(json);
        } catch (JSONException ex) {
            Log.d("Parsing Error!", "Can't parse the string" +ex.toString());
            Log.d("STRING_FROM_SERVER", json);
        }