array ( 0 => 'index.php', 1 => 'PHP Manual', ), 'head' => array ( 0 => 'UTF-8', 1 => 'es', ), 'this' => array ( 0 => 'jsonserializable.jsonserialize.php', 1 => 'JsonSerializable::jsonSerialize', ), 'up' => array ( 0 => 'class.jsonserializable.php', 1 => 'JsonSerializable', ), 'prev' => array ( 0 => 'class.jsonserializable.php', 1 => 'JsonSerializable', ), 'next' => array ( 0 => 'ref.json.php', 1 => 'Funciones de JSON', ), 'alternatives' => array ( ), 'source' => array ( 'lang' => 'es', 'path' => 'reference/json/jsonserializable/jsonserialize.xml', ), ); $setup["toc"] = $TOC; $setup["toc_deprecated"] = $TOC_DEPRECATED; $setup["parents"] = $PARENTS; manual_setup($setup); ?>
(PHP 5 >= 5.4.0, PHP 7, PHP 8)
JsonSerializable::jsonSerialize — Especifica los datos que deberían serializarse para JSON
Serializa el objeto a un valor que puede ser serializado de forma nativa por json_encode().
Esta función no tiene parámetros.
Devuelve los datos que pueden ser serializados por json_encode(), los cuales son un valor de cualquier tipo distinto de resource.
Ejemplo #1 Ejemplo de JsonSerializable::jsonSerialize() devolviendo un array
<?php
class ArrayValue implements JsonSerializable {
public function __construct(array $array) {
$this->array = $array;
}
public function jsonSerialize() {
return $this->array;
}
}
$array = [1, 2, 3];
echo json_encode(new ArrayValue($array), JSON_PRETTY_PRINT);
?>
El resultado del ejemplo sería:
[ 1, 2, 3 ]
Ejemplo #2 Ejemplo de JsonSerializable::jsonSerialize() devolviendo un array asociativo
<?php
class ArrayValue implements JsonSerializable {
public function __construct(array $array) {
$this->array = $array;
}
public function jsonSerialize() {
return $this->array;
}
}
$array = ['foo' => 'bar', 'quux' => 'baz'];
echo json_encode(new ArrayValue($array), JSON_PRETTY_PRINT);
?>
El resultado del ejemplo sería:
{ "foo": "bar", "quux": "baz" }
Ejemplo #3 Ejemplo de JsonSerializable::jsonSerialize() devolviento un integer
<?php
class IntegerValue implements JsonSerializable {
public function __construct($number) {
$this->number = (integer) $number;
}
public function jsonSerialize() {
return $this->number;
}
}
echo json_encode(new IntegerValue(1), JSON_PRETTY_PRINT);
?>
El resultado del ejemplo sería:
1
Ejemplo #4 Ejemplo de JsonSerializable::jsonSerialize() devolviendo un string
<?php
class StringValue implements JsonSerializable {
public function __construct($string) {
$this->string = (string) $string;
}
public function jsonSerialize() {
return $this->string;
}
}
echo json_encode(new StringValue('¡Hola!'), JSON_PRETTY_PRINT);
?>
El resultado del ejemplo sería:
"¡Hola!"