PHP Reference ยท Standard PHP Library and Classes
The JsonSerializable interface
Reference for the PHP JsonSerializable interface: control what json_encode() outputs for your objects with jsonSerialize(), hide fields and nest objects.
By default json_encode() turns an object into a JSON object made of its public properties. That is rarely what you want for domain classes with private state, computed values or dates. JsonSerializable hands you control: implement jsonSerialize() and return whatever should be encoded in the object's place.
The returned value can be an array, a scalar, null, or another object (which is serialized in turn, including other JsonSerializable objects).
class Tag implements JsonSerializable { public function __construct(private string $name) {} public function jsonSerialize(): mixed { return ['name' => $this->name]; } }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
interface JsonSerializable { public function jsonSerialize(): mixed; }
| Name | Description |
|---|---|
jsonSerialize() |
Takes no parameters. Returns the data that json_encode() should encode instead of the object. |
Return value: any value that json_encode() can encode (mixed). A list-shaped array becomes a JSON array, an associative array becomes an object.
Errors / Exceptions: exceptions thrown inside jsonSerialize() propagate out of json_encode(). Encoding failures (for example invalid UTF-8 in a returned string) follow the usual json_encode() rules; pass JSON_THROW_ON_ERROR to get a JsonException.
Usage notes
- Used only by
json_encode(). It does not affectserialize(),var_export()orvar_dump(). - It decides the shape. Return an empty array and you get
[], not{}. Returnnew stdClassor useJSON_FORCE_OBJECTwhen you need an empty object. - Nested objects are visited. If the returned array contains other
JsonSerializableobjects, theirjsonSerialize()runs too. - Return plain data. Returning arrays, scalars or other objects is fine; avoid handing back an object that leads straight back to this one, which would loop.
- Without the interface, only public properties are encoded, as the second example shows. Typed properties that are uninitialized are skipped.
- Backed enums encode as their scalar value automatically; no interface is needed.
- Dates: a
DateTimeInterfaceencodes as an object withdate,timezone_typeandtimezone. Return$date->format(DATE_ATOM)yourself for something friendlier. - Decoding is separate.
json_decode()gives arrays orstdClass; rebuild your classes with a named constructor.
Related
json_encode(),json_decode(),JsonException,stdClass- Lessons: JSON, Magic methods