【问题标题】:json return in laraveljson 在 laravel 中返​​回
【发布时间】:2014-10-26 08:04:04
【问题描述】:

我有一个控制器,它返回如下 JSON 字符串

$response = Response::json(array("success"=>"true","token"=>$token));

返回值是{"success":"true","token":{}},但是当我放一个静态值时

$response = Response::json(array("success"=>"true","token"=>"12345"));

返回值正确{"success":"true","token":"12345"}

变量$token在插入数据库时​​生成,但没有正确返回。

令牌是使用 webpatser UUID 生成的:Uuid:generate();

问题:我该如何解决这个问题?


UPD:

var_dump($token) 结果:

["string":protected]=> string(36) "d0c95650-3269-11e4-a55e-15cdb906eead"

UPD 2:

$response = Response::json(array("success"=>"true","token"=>$token[0]));

returns {"success":"true","token":NULL}

尝试将 $token 的值更改为其他变量,例如

$test = "test";

然后

$response = Response::json(array("success"=>"true","token"=>$test));

返回{"success":"true","token":"test"}

【问题讨论】:

  • 你检查过$tokenvar_dump() 的值吗?它显示了什么?
  • 试试$token的第一个元素:$response = Response::json(array("success"=>"true","token"=>$token[0]));
  • 查看$token的值,可能为空
  • @HAL9000 var_dump($token) 结果如下: ["string":protected]=> string(36) "d0c95650-3269-11e4-a55e-15cdb906eead"
  • @vikramjain 我试过你的建议,我得到了 NULL。查看更新

标签: php json laravel-4


【解决方案1】:

用户 foreach 获取 $token 并从中获取价值。将其分配到某个变量中并在您的响应中使用它。

例如。

$my_tocken = "";
foreach ($tocken as $real_tocken){
  $my_tocken = $real_tocken;
}

现在构建您的响应,就像您通常使用测试变量构建的那样。

【讨论】:

    【解决方案2】:

    您的$token 变量包含一个对象,该对象具有protected 成员的值,json 编码器无法访问该对象。

    可能应该有一些方法来获取它,比如$token->getValue() 或类似的东西。在这种情况下,您需要将您的回复更改为

    $response = Response::json(array("success"=>"true","token"=>$token->getValue()));
    

    如果你能提供get_class_methods()的类方法,我或许可以进一步建议。

    作为一种解决方法(实际上这不是首选的方法),您可以尝试使用reflection

    <?php
    header('Content-Type: text/plain; charset=utf-8');
    
    class A {
        protected $test = 'xxx';
    
        public function change(){
            $this->test = 'yyy';
        }
    }
    
    $a = new A();
    $a->change();
    
    $class    = new ReflectionClass(get_class($a));
    $property = $class->getProperty('test');
    
    $property->setAccessible(true); // "Dark "magic"
    
    echo $property->getValue($a); // "Dark magic"
    ?>
    

    演出:

    yyy
    

    所以在你的代码中可能是这样的:

    $class    = new ReflectionClass(get_class($token));
    $property = $class->getProperty('string');
    
    $property->setAccessible(true);
    
    $token = $property->getValue($token);
    
    $response = Response::json(array("success"=>"true","token"=>$token));
    

    【讨论】:

      【解决方案3】:

      您需要通过类本身的 getter 方法来提供它。

      所以在课堂上:

      public function getData()
      {
        return $this->string;
      }
      

      在你的程序中:

      $token->getData();
      

      【讨论】:

      • 试过这个,值仍然为空。问题似乎出在 uuid 生成器中,因为我尝试将其他变量作为令牌的值传递并且它工作正常。
      猜你喜欢
      • 1970-01-01
      • 2016-09-04
      • 1970-01-01
      • 2017-03-25
      • 2017-05-24
      • 2019-06-30
      • 2018-05-31
      • 2017-11-23
      • 1970-01-01
      相关资源
      最近更新 更多