JsonSerializable

2013/03/11 17:17

JSON is the modern data format used in "AJAX" applications. As the leading language for the Web PHP course has support for handling JSON data: You can pass any data to json_encode() and the function will create a JSON representation of this data:

[php]

<?php
echo json_encode(array(1,2,3,4));
?>

[1,2,3,4]
[/php]

This also works for objects:

[php]

<?php
$o = new stdclass;$o->a = 42;
echo json_encode($o); ?> {"a":42} [/php] Wonderful. But the world isn't that easy. 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. So let's take a look: [php] <?php class JsonTest implements JsonSerializable { private$a, $b; public function __construct($a, $b) {$this->a = $a;$this->b = $b; } public function jsonSerialize() { return$this->a + $this->b; } } echo json_encode(new JsonTest(23, 42)); ?> 65 [/php] Now this example in itself is of course useless, but let's create a bigger structure, which includes a few of these objects: [php] <?php$data = array(
new stdClass();
new JsonTest(1,2),
new JsonTest(3,4),
array(5,6)
);
echo json_encode(\$data);
?>

[{},3,7,[5,6]]

[/php]

Of course you'd usually have more complex serialization logic, but that's left to you.

Now almost certainly somebody will ask "and what about the other way round?" - The only answer there is: Sorry there we can't do much. JSON doesn't encode and meta-information so our generic parser in json_decode() can't do anything special. But anyways: The new interface will certainly be useful.

0
0 收藏

0 评论
0 收藏
0