Using JsonSerializable in an Object (ok)
https://riptutorial.com/php/example/7722/using-jsonserializable-in-an-object
Last updated
Was this helpful?
https://riptutorial.com/php/example/7722/using-jsonserializable-in-an-object
Last updated
Was this helpful?
Đã thực hành:
C:\xampp\htdocs\php\model.php
C:\xampp\htdocs\php\index.php
========== :) ===========
When you build REST API's, you may need to reduce the information of an object to be passed to the client application. For this purpose, this example illustrates how to use the JsonSerialiazble
interface.
In this example, the class User
actually extends a DB model object of a hypotetical ORM.
Add JsonSerializable
implementation to the class, by providing the jsonSerialize()
method.
Now in your application controller or script, when passing the object User to json_encode()
you will get the return json encoded array of the jsonSerialize()
method instead of the entire object.
Will return:
This will both reduce the amount of data returned from a RESTful endpoint, and allow to exclude object properties from a json representation.
json_encode()
#To avoid using JsonSerializable, it is also possible to use private or protected properties to hide class information from json_encode()
output. The Class then does not need to implement \JsonSerializable.
The json_encode() function will only encode public properties of a class into JSON.