search

Home  >  Q&A  >  body text

Difference between toJson method and jsonSerialize method?

When I look at the Illuminate\Support\MessageBag class methods, the class looks like this:

use JsonSerializable;
use Illuminate\Contracts\Support\Jsonable;
....

class MessageBag implements Jsonable, JsonSerializable...

/*
 * Convert the object to its JSON representation.
 */
public function toJson ($options = 0) {
    return json_encode($this->jsonSerialize(), $options);
}

/*
 *Convert the object into something JSON serializable.
 */
public function jsonSerialize() {
    return $this->toArray();
}

Please tell me, seniors, what is the difference between the toJson method and the jsonSerialize method? When will it be called implicitly?

大家讲道理大家讲道理2782 days ago750

reply all(4)I'll reply

  • 天蓬老师

    天蓬老师2017-05-16 13:02:38

    Refer to the document: http://php.net/manual/zh/json...
    Upload the code:

    class j implements JsonSerializable{
        public function jsonSerialize(){
            return "Hello world!";
        }
    }
    echo json_encode(new j());

    JsonSerializable itself specifically serves json_encode serialization, and toJson is just the Jsonable method of laravel.

    In other words, when you use json_encode to serialize this object, the jsonSerialize method will be called.

    And your toJson usually just encapsulates the json_encode function, just for semantics.

    reply
    0
  • phpcn_u1582

    phpcn_u15822017-05-16 13:02:38

    Like this?

     public function jsonSerialize()
        {
            return $this->toArray();
        }
    
    public function toJson($options = 0)
        {
            return json_encode($this->jsonSerialize(), $options);
        }    

    reply
    0
  • PHP中文网

    PHP中文网2017-05-16 13:02:38

    I don’t know much about it, so I searched it for you:
    http://www.cnblogs.com/gniele...

    reply
    0
  • phpcn_u1582

    phpcn_u15822017-05-16 13:02:38

    Thanks for the invitation!

    Because I have never used larval, can you post the specific code of toJson method and jsonSerialize method

    reply
    0
  • Cancelreply