Last Updated: October 11, 2021
·
3.319K
· seiffert

JSON-encode objects: JsonSerializable

PHP 5.4 introduces some great improvement in its JSON extension. One of them is the interface JsonSerializable.

JsonSerializable

Objects implementing this interface have to provide a method called jsonSerialize. This method should return any data of the object that should be transformed to JSON when json_encode is called with this object as parameter.

<?php

class TreeNode implements JsonSerializable
{
    private $value;

    private $children = array();

    public function __construct($value)
    {
        $this->value = $value;
    }

    // accessor methods for $this->children omitted

    public function jsonSerialize()
    {
        return ['value' => $this->value,
                'children' => $this->children];
    }
}

$t = new TreeNode(1);
$t->addChild(new TreeNode(2));

echo json_encode($t);

// output:
// {"value":1,"children":[{"value":2,"children":[]}]}

JSON_PRETTY_PRINT

Reading JSON (or better: parsing JSON in your head) is very painful if it isn't formatted properly. With the new option JSON_PRETTY_PRINT, PHP is capable of producing (almost) human readable JSON:

echo json_encode($t, JSON_PRETTY_PRINT);

// output: 
// {
//     "value": 1,
//     "children": [    
//         {
//             "value": 2,
//             "children": [
// 
//             ]
//         }
//     ]
// }

Further Reading

1 Response
Add your response

nice

over 1 year ago ·