在PHP中将类对象转换为JSON

时间:2016-07-12 15:38:56

标签: php json oop laravel-5.2

我在Laravel的控制器上获得了Class对象响应。

object(DayJibe\Core\User\Entities\User)#221 (5) {
 ["id":"DayJibe\Core\User\Entities\User":private]=>
 int(1)
 ["name":"DayJibe\Core\User\Entities\User":private]=>
 string(5) "admin"
 ["email":"DayJibe\Core\User\Entities\User":private]=>
 string(15) "admin@gmail.com"
 ["is_admin":"DayJibe\Core\User\Entities\User":private]=>
 string(1) "N"
 }

现在我需要将此响应转换为JSON。有没有办法做到这一点?

2 个答案:

答案 0 :(得分:0)

好的,我做了什么来解决这个问题。         $ session ="如上所述的Class Object&#34 ;;

    $objClass = new \ReflectionClass($session);

    $classProperties = $objClass->getProperties();

    foreach ($classProperties as $propertie)
    {
        $propertie->setAccessible(true);
        $arrayForJSON[$propertie->getName()] = $propertie->getValue($session);
    }

    return $response  = Response()->json($arrayForJSON);

$ response =" {" id":1," name":" admin"," email":& #34; admin@gmail.com"," is_admin":" N"" generatedToken":" eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9 .eyJzdWIiOjEsImlzcyI6Imh0dHA6XC9cL2RheWppYmUubG9jYWxob3N0LmNvbVwvYXBpXC92MS4wXC9zZXNzaW9ucyIsImlhdCI 6MTQ2ODM0NjQ0OCwiZXhwIjoxNDY4MzUwMDQ4LCJuYmYiOjE0NjgzNDY0NDgsImp0aSI6IjU2ZTUzOTgxNTliNDA4M2I4Y2M5MmNlNWE4OGY0MDY3In0 .oLq6L8LM36n9KB2KN8asoKKfhVYOeBVUz1jjfjVGfL4"}&#34 ;;

答案 1 :(得分:0)

告诉用户为您提供自己的JSON表示。

class User {

    private $id;
    private $name;
    private $email;
    private $is_admin;

    /**
     * Gives a JSON representation of this user
     * @return string
     */
    public function toJson() {
        return json_encode([
            'id' => $this->id,
            'name' => $this->name,
            'email' => $this->email,
            'is_admin' => (bool) $this->is_admin
        ]);
    }

}
来自你的控制器的

就像这样调用它:

$userJson = $session->toJson();