博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
JsonSerializable
阅读量:6281 次
发布时间:2019-06-22

本文共 1650 字,大约阅读时间需要 5 分钟。

  hot3.png

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 and the function will create a JSON representation of this data:

[php]

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

This also works for objects:

[php]

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]

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]

[{},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 can't do anything special. But anyways: The new interface will certainly be useful.

转载于:https://my.oschina.net/clearchen/blog/112974

你可能感兴趣的文章
并查集 4104 这是一棵树吗
查看>>
servlet流(转摘)
查看>>
Android 连接 SQL Server (jtds方式)——上
查看>>
折射向量计算(Refraction Vector Calculation)
查看>>
常见的压缩文件格式案例tarZ
查看>>
QT环境下实现UI界面的“拼图游戏”
查看>>
WIN7 64位操作系统 无法找到Access驱动
查看>>
怎样解题
查看>>
HDU - 4901 The Romantic Hero(dp)
查看>>
LightOJ - 1246 Colorful Board(DP+组合数)
查看>>
sqlserver distribution分发alwayson搭建
查看>>
力扣算法题—055跳跃游戏
查看>>
Nginx服务安装指南
查看>>
layer遮罩层 简单的遮罩层
查看>>
vue中使用腾讯云Im
查看>>
java FTP上传文件
查看>>
ubuntu 安装 eslint
查看>>
【转】围观 Joomla, Wordpress 和 Drupal
查看>>
用JS做关灯游戏(初级)
查看>>
vue.js学习 自定义过滤器使用(2)
查看>>