尽管JSON响应明显正确,json_decode仍会返回NULL

时间:2015-02-20 16:59:45

标签: php json

我正在尝试使用json_decode解释来自Web服务调用的响应。 JSON似乎有效(已经在线验证器等检查过)但json_decode仍然返回NULL。

Web服务返回的数据如下:

[{"id":"cc9dfabc36abc54c5a7","extension":"001","links":{"self":"https:\/\/someurl\/api\/response\/@me\/001\/cc9dfabc36abc54c5a7"}}]

Web服务响应数据存储在$result中。我解码JSON的代码如下:

if (is_null(json_decode($result))){
        $callObj = json_decode($result, true);  
        $callID = $callObj->extension;  
    }
    else
    {
        echo "<BR>Could not decode response <BR>";
        $callID = 'error';
    }           
    return $callID; 

1 个答案:

答案 0 :(得分:1)

第一次测试不应该是否定的(!is_null)?只有当它不是null(因此是一个json对象)时才应该继续。

另外,第二个json_encode函数传递'true'作为第二个参数,它使返回的对象成为关联数组而不是对象。

以下修改似乎对我有用。

if (!is_null(json_decode($result))){
    $callObj = json_decode($result, true);
    $callID = $callObj[0]['extension'];
}
else
{
    echo "<BR>Could not decode response <BR>";
    $callID = 'error';
}
return $callID;
相关问题