James McFadden {web developer}

Implement JsonSerializable to control how objects are serialised into JSON

I assumed that json_encode would make use of PHP’s __toString() magic method, giving me the ability to manage how my object is processed. Turns out it doesn’t. However, if you’re using PHP 5.4 or later, you can make use of the JsonSerializable interface which allows specification of what object data should be serialised:

/**
 * @author James McFadden <[email protected]>
 */
class Nova_Dto_Vacancy implements JsonSerializable
{
    protected $_vacancy;
    
    public function __construct(Model_Vacancy $vacancy)
    {
        $this->_vacancy = $vacancy;
    }
    
    public function getData()
    {
        return array(
            'Name' => $this->_vacancy->getName()
        );
    }
    
    public function jsonSerialize()
    {
        return $this->getData();
    }
}
comments powered by Disqus