【问题标题】:PHP Json_Decode return Null [duplicate]PHP Json_Decode 返回 Null [重复]
【发布时间】:2012-09-13 12:23:21
【问题描述】:

可能重复:
json_decode returns NULL after webservice call


我正在开发一个面向 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);
    }
}

【问题讨论】:

  • 你能告诉我们更多你的代码吗,到目前为止应该没有问题......

标签: php json codeigniter


【解决方案1】:

您的 JSON 使用 JSONLint 进行验证。它可能是通过 url 传递的不需要的空格或字符。我认为如果您要添加干净的 JSON 字符串,则可能不会出现此问题。尝试在json_decode() 之后添加json_last_error() 以确定确切的问题。它应该是这样的:

        $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);

【讨论】:

  • 我的服务器是 5.2 last_error() 将无法正常工作
【解决方案2】:

看看这个链接

PHP json_decode() returns NULL with valid JSON?

json_decode() returns null issues

json_decode returns NULL after webservice call

我想是因为UTF-8 BOM

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

试试这种格式。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-27
    • 1970-01-01
    • 2018-06-19
    • 2019-04-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多