0

重複の可能性:
Web サービスの呼び出し後に json_decode が NULL を返す


私はRESTサービス指向のアプリを開発しています。ログインの場所で、ユーザー名とパスワードを投稿すると、次のjsonが返されます

{"id":"4","username":"sam","redirect":"clients/home"}

その後、json_decode() を実行しようとすると、NULL が表示されます。サーバーが PHP 5.2.12 であり、JSON_Decode をサポートしている問題を教えてください。

function login()
{
    $result=$this->rest->request("http://localhost/account/users/login","POST");
    $qry['result']=json_decode($result);
    var_dump($qry['result']);
    foreach($qry as $result)
    {
        $this->session->set_userdata('id',$result->id);
        $this->session->set_userdata('username',$result->username);
        redirect($result->redirect);
    }
}
4

2 に答える 2

2

JSONLint を使用して JSON を検証します。URL 経由で渡される不要なスペースまたは文字である可能性があります。クリーンな JSON 文字列を追加すれば、この問題は発生しないと思います。json_last_error()afterを追加しjson_decode()て、正確な問題を特定してみてください。次のようになります。

        $qry['result']=json_decode($result);
        switch(json_last_error())
        {
            case JSON_ERROR_DEPTH:
                $error =  ' - Maximum stack depth exceeded';
                break;
            case JSON_ERROR_CTRL_CHAR:
                $error = ' - Unexpected control character found';
                break;
            case JSON_ERROR_SYNTAX:
                $error = ' - Syntax error, malformed JSON';
                break;
            case JSON_ERROR_NONE:
            default:
                $error = '';                    
        }
        if (!empty($error))
            throw new Exception('JSON Error: '.$error);
于 2012-09-21T05:08:51.853 に答える
0

このリンクを見てください

PHP json_decode()は有効なJSONでNULLを返しますか?

json_decode()はnullの問題を返します

json_decodeは、Webサービスの呼び出し後にNULLを返します

のせいだと思いますUTF-8 BOM

if(get_magic_quotes_gpc()){
  $d = stripslashes($result);
}else{
  $d = $result;
}
$d = json_decode($d,true);

この形式で試してください。

于 2012-09-21T04:57:31.633 に答える