JsonSerializable类 - json函数(JavaScript对象符号)
JsonSerializable类
(PHP 5 >= 5.4.0, PHP 7)
实现JsonSerializable
的类可以在json_encode()
时定制他们的 JSON 表示法。
JsonSerializable { /* 方法 */ abstract public jsonSerialize ( void ) : mixed }
JsonSerializable::jsonSerialize
(PHP 5 >= 5.4.0, PHP 7)
指定需要被序列化成 JSON 的数据
说明
abstractpublicJsonSerializable::jsonSerialize (void) : mixed序列化物体(Object)成能被 json_encode() 原生地序列化的值。
返回值
返回能被 json_encode() 序列化的数据, 这个值可以是除了 resource 外的任意类型。
范例
JsonSerializable::jsonSerialize() 例子 returning an array
以上例程会输出:
[ 1, 2, 3 ]
JsonSerializable::jsonSerialize() 例子 返回了一个关联数组 array
以上例程会输出:
{ "foo": "bar", "quux": "baz" }
JsonSerializable::jsonSerialize() 例子 返回一个 integer
以上例程会输出:
1
JsonSerializable::jsonSerialize() 例子 返回一个 string
以上例程会输出:
"Hello!"
A good example on when you would use functionality like this is when working with objects. json_encode() will take a DateTime and convert it to: { "date":"2013-01-31 11:14:05", "timezone_type":3, "timezone":"America\/Los_Angeles" } This is great when working with PHP, but if the Date is being read by Java. The Java date parser doesn't know what to do with that. But it does know what to do with the ISO8601 format...
Nested json serializable objects will be serialized recursively. No need to call ->jsonSerialize() on your own. It is especially useful in collections.
Here's a small test/proof that makes it easy to see some comparative results. Null was the one I was interested in since it was not documented: Output is: Null -> null Array -> [1,2,3] Assoc. -> {"a":1,"b":3,"c":4} Int -> 5 String -> "Hello, World!" Object -> {"a":1,"b":3,"c":4}
simonsimcity at gmail dot com is wrong, you can throw exceptions in this but it will wrap with another exception so his example outputs PHP Fatal error: Uncaught exception 'RuntimeException' with message 'It failed!' in -:8 Stack trace: #0 [internal function]: Foo->jsonSerialize() #1 -(16): json_encode(Object(Foo)) #2 {main} Next exception 'Exception' with message 'Failed calling Foo::jsonSerialize()' in -:16 Stack trace: #0 -(0): json_encode() #1 {main} thrown in - on line 16 PHP 5.4.39
For those who are also lazy. You cannot just include $this and expect it to work. For example, this won't work: You have to define the things manually, so this will work.
You can't throw exceptions in here. If you do, you'll get an exception with the message "Failed calling FooClass::jsonSerialize()" and the stacktrace will start at where you called the json_encode() method. Here's a code-example: class Foo implements JsonSerializable { private $triggerError = true; public function jsonSerialize() { if ($this->triggerError) { throw new RuntimeException("It failed!"); } return (array)$this; } } // Will throw an exception like new Exception("Failed calling Foo::jsonSerialize()") json_encode(new Foo());
simple functions to make life easier. I wanted a way to have a as property value the return value of a method in order to have it initialized. example class portItem implements JsonSerializable{ private $idPort; private $location; private $portLanguages; public function getLocation() { if(!isset($this->location)){ return new locationItem(); } return $this->location; } public function setLocation($location) { $this->location = $location; } public function setidPort($idPort){ $this->idPort=$idPort; } public function getidPort(){ if(!isset($this->idPort)){ return 0; } return intval($this->idPort); } public function setPortLanguages($portLanguages){ $this->portLanguages=$portLanguages; } public function getPortLanguages(){ if(!isset($this->portLanguages)){ return new genericItems(); } return $this->portLanguages; } public function getCategoryLanguages(){ if(!isset($this->portLanguages)){ return new genericItems(); } return $this->portLanguages; } public function getPortLanguageAtIndex($index=false){ if(!$index){ $index=0; } return $this->portLanguages[$index]; } public function setPortLanguageAtIndex($index,$language){ $this->portLanguages[$index]=$language; } public function jsonSerialize() { $dataConverter = new dataConverter(); return $dataConverter->convertToJson($this); } } Wit 2 ways you can automatically convert for json. 1.by reading properties public function convertToJson($object){ /*approch by using object properties*/ $class = get_class($this); $json = array(); $properties = get_class_vars($class); $keys = array_keys($properties); $plength = count($keys); for($i=0;$i$method(); } } return $json; } public function convertToJson($object){ /*approch by using object methods*/ $class = get_class($object); $json = array(); $methods = get_class_methods($class); $plength = count($methods); $json = array(); for($i=0;$i$methods[$i](); } } } return $json; } By using this method the result will be a json with value for properties initialized according to each method. Things to note 1.if you are using the reading properties approach the code cant' work outside of the class for private properties, because they are nto visible, you have to put it the code directly to public function jsonSerialize() {} in order to work. 2.For both approaches has method seems not to be case sensitive else you are going to have problems, i strongly suggest to pay attention in naming convention between property names and method names idPort =>setIdPort() =>getIdPort() (i know my class is done not that way). 3.both approaches since you call method without knowing the arguments you need to pay attention in arguments for getter methods where applicable, check my example public function getPortLanguageAtIndex($index=false){ if(!$index){ $index=0; } return $this->portLanguages[$index]; } that's why i have set it to optional argument. If you don't do that php will complain about missing argument parameter in method XXX.
鹏仔微信 15129739599 鹏仔QQ344225443 鹏仔前端 pjxi.com 共享博客 sharedbk.com
免责声明:我们致力于保护作者版权,注重分享,当前被刊用文章因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理!邮箱:344225443@qq.com)
图片声明:本站部分配图来自网络。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!
内容声明:本文中引用的各种信息及资料(包括但不限于文字、数据、图表及超链接等)均来源于该信息及资料的相关主体(包括但不限于公司、媒体、协会等机构)的官方网站或公开发表的信息。部分内容参考包括:(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供参考使用,不准确地方联系删除处理!本站为非盈利性质站点,本着为中国教育事业出一份力,发布内容不收取任何费用也不接任何广告!)