PHP JSON Using JsonSerializable in an Object


PHP 5.x5.4

When you build REST API's, you may need to reduce the information of an object to be passed to the client application. For this purpose, this example illustrates how to use the JsonSerialiazble interface.

In this example, the class User actually extends a DB model object of a hypotetical ORM.

class User extends Model implements JsonSerializable {
    public $id;
    public $name;
    public $surname;
    public $username;
    public $password;
    public $email;
    public $date_created;
    public $date_edit;
    public $role;
    public $status;

    public function jsonSerialize() {
        return [
            'name' => $this->name,
            'surname' => $this->surname,
            'username' => $this->username

Add JsonSerializable implementation to the class, by providing the jsonSerialize() method.

public function jsonSerialize()

Now in your application controller or script, when passing the object User to json_encode() you will get the return json encoded array of the jsonSerialize() method instead of the entire object.


Will return:

{"name":"John", "surname":"Doe", "username" : "TestJson"}

properties values example.

This will both reduce the amount of data returned from a RESTful endpoint, and allow to exclude object properties from a json representation.

Using Private and Protected Properties with json_encode()

To avoid using JsonSerializable, it is also possible to use private or protected properties to hide class information from json_encode() output. The Class then does not need to implement \JsonSerializable.

The json_encode() function will only encode public properties of a class into JSON.


class User {
    // private properties only within this class
    private $id;
    private $date_created;
    private $date_edit;

    // properties used in extended classes
    protected $password;
    protected $email;
    protected $role;
    protected $status;

    // share these properties with the end user        
    public $name;
    public $surname;
    public $username;

    // jsonSerialize() not needed here

$theUser = new User();



string(44) "{"name":null,"surname":null,"username":null}"