Looking for more information on how to do PHP the right way? Check out PHP: The Right Way

SitePoint PHP Blog:
How to Use the JsonSerializable Interface
May 05, 2014 @ 16:50:28

Matrin Hardy has a new tutorial posted to the SitePoint PHP blog today showing you how to use the JsonSerializable interface to work with objects and converting them to JSON.

Over the past few years JSON has taken over as the king of data interchange formats. Before JSON, XML ruled the roost. It was great at modeling complex data but it is difficult to parse and is very verbose. [...] I think we could all agree that writing less code that in turn requires less maintenance and introduces less bugs is a goal we would all like to achieve. In this post, I’d like to introduce you to a little known interface that was introduced in PHP 5.4.0 called JsonSerializable.

He splits the rest of the post out into three different parts: the "ugly" method of converting a sample Customer object into a JSON string (through an array), the "bad" method using a "toJson" method and finally the "good", implementing a class that implements the JsonSerializable interface for easy JSON-ification.

tagged: jsonserializable interface tutorial introduction beginner

Link: http://www.sitepoint.com/use-jsonserializable-interface/

Johannes Schluter's Blog:
Jason, let me help you!
Jun 04, 2010 @ 15:02:15

In a new post to his blog Johannes Schluter looks at a helpful new inclusion into the latest versions of the PHP trunk - a new JSON serialization interface included in the core.

For many PHP objects the JSON-representation of the data is a bit more complex.for instance what about private properties or maybe you want to calculate some inner values? - In PHP 5.3 you were on your own. but thanks to Sara there's hope in sight: the new interface JsonSerializable. Classes implementing this interface have to provide a method jsonSerialize() which will be called by json_encode() and has to return a JSON-compatible representation of the data by doing whatever you want.

He gives two examples of this new feature in action - a simple one that just spits out some basic JSON as a result of the output of a class and the other that's a bit more technical, involving multiple class isntances, a stdClass and a normal array.

tagged: json jsonserializable encode interface implements

Link:


Trending Topics: