Using JsonSerializable in an Object

suggest change

When you build REST APIs, 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 JsonSerializable interface. Since PHP 8.1, jsonSerialize() should declare the return type mixed.

In this example, the class User actually extends a DB model object of a hypothetical 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, passing the User object to json_encode() encodes the array from jsonSerialize() instead of the entire object.

json_encode($User);

With name, surname, and username set to those strings, it returns:

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

properties values example.

This will both reduce the amount of data returned from a RESTful endpoint, and allow you 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.

<?php

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();

var_dump(json_encode($theUser));

Output:

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

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents