php - JSONException : Value of type java. lang.String 无法转换为 JSONObject

标签 php android web-services

我遇到了一个问题,一个有效的 JSON 字符串不能变成一个 JSON 对象。

我已经测试了来自服务器的响应,它是一个有效的 JSON。

网上查了一下,是UTF-8与DOM的问题。但是即使我将 Notepad++ 中的字符集更改为没有 DOM 的 UTF-8,仍然会出现同样的错误。

我的代码:

<?php
    require_once("Connection/conn.php");


    //parse JSON and get input
    $json_string = $_POST['json'];
    $json_associative_array = json_decode($json_string,true);

    $userId = $json_associative_array["userId"];
    $password = $json_associative_array["password"];
    $userType = $json_associative_array["userType"];    

    //get the resources
    $json_output_array = array();

    $sql = "SELECT * FROM account WHERE userId = '$userId' AND password = '$password' AND userType = '$userType'";  
    $result = mysql_query($sql);  

    //access success?
    if (!$result) {
        die('Invalid query: ' . mysql_error());
        $json_output_array["status"] = "query failed";
    }
    else{
        $json_output_array["status"] = "query success";
    }

    //find the particular user?
    if (mysql_num_rows($result) > 0){
        $json_output_array["valid"] = "yes";
    }
    else{
        $json_output_array["valid"] = "no";
    }

    //output JSON 
    echo json_encode($json_output_array);
?>

安卓代码:

public boolean login() {
        // instantiates httpclient to make request
        DefaultHttpClient httpClient = new DefaultHttpClient();

        // url with the post data
        String url = SERVER_IP + "/gc/login.php";

        JSONObject holder = new JSONObject();
        try {
            holder.put("userId", "S1");
            holder.put("password", "s12345");
            holder.put("userType", "supervisor");
        } catch (JSONException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        Log.d("JSON", holder.toString());


        // HttpPost
        HttpPost httpPost = new HttpPost(url);


        //FormEntity
        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("json", holder.toString()));

        try {
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        } catch (UnsupportedEncodingException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        // execution and response
        boolean valid = false; 
        try {
            HttpResponse response = httpClient.execute(httpPost);

            Log.d("post request", "finished execueted");
            String responseString = getHttpResponseContent(response);
            Log.d("post result", responseString);

            //parse JSON
            JSONObject jsonComeBack = new JSONObject(responseString);
            String validString = jsonComeBack.getString("valid");
            valid = (validString.equals("yes"))?true:false;

        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }



        return valid;

    }

    private String getHttpResponseContent(HttpResponse response) {

        String responseString = "";

        try {
            BufferedReader rd = new BufferedReader(new InputStreamReader(
                    response.getEntity().getContent()));

            String line = "";

            while ((line = rd.readLine()) != null) {
                responseString += line ;
            }
            rd.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return responseString;
    }

JSON 来自服务器:

{
    "status": "query success",
    "valid": "yes"
}

取消格式化 JSON:

{"status":"查询成功","valid":"是"}

当我将其复制到 Notepad++ 中时,它变成了 ?{"status":"query success","valid":"yes"} 似乎有一个看不见的角色。

最佳答案

我用 solution 修复了它由 MuhammedPasha 提供,它对 JSON 字符串进行子字符串化以删除不可见字符。然后我从 1 中提取 JSON 字符串来解决我的问题。

有一种方法可以检测那些不可见字符,将日志结果复制到notepad++中。(复制!不要打字!)如果有?(问号),则表明存在一些不可见字符。

关于php - JSONException : Value of type java. lang.String 无法转换为 JSONObject,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13368739/

相关文章:

php - Mysql到Mysqli

php - 无法使用 CodeIgniter 插入数据库

android - 如何在 MPAndroidChart 中设置颜色?

java - Android:联网情况下的随机生成(多人游戏)

.net - SOA : WCF 中转换层的替代方案

php - 在 OS X 上,安装 php_pdo_pgsql、pgsql.so 后,警告 : dynamic library warnings - image not found

php - 500 内部错误 - 连接到外部 WordPress 数据库时 PHP 超时

android - Android 的 FragmentTransaction.commit() 方法线程安全吗?

spring - 从数据库或Java对象动态加载spring bean属性)

ios - 带身份验证的 CGImageSourceCreateWithURL