JsonSerializable::jsonSerialize

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

JsonSerializable::jsonSerializeEspecifica os dados que devem ser serializados para JSON

Descrição

public JsonSerializable::jsonSerialize(): mixed

Serializa o objeto para um valor que pode ser serializado nativamente por json_encode().

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

Retorna dados que podem ser serializados por json_encode(), que é um valor de qualquer tipo que não seja um resource.

Exemplos

Exemplo #1 Exemplo de JsonSerializable::jsonSerialize() retornando um array

<?php
class ArrayValue implements JsonSerializable {
private
$array;
public function
__construct(array $array) {
$this->array = $array;
}

public function
jsonSerialize(): mixed {
return
$this->array;
}
}

$array = [1, 2, 3];
echo
json_encode(new ArrayValue($array), JSON_PRETTY_PRINT);
?>

O exemplo acima produzirá:

[
    1,
    2,
    3
]

Exemplo #2 Exemplo de JsonSerializable::jsonSerialize() retornando um array associativo

<?php
class ArrayValue implements JsonSerializable {
private
$array;
public function
__construct(array $array) {
$this->array = $array;
}

public function
jsonSerialize(): mixed {
return
$this->array;
}
}

$array = ['foo' => 'bar', 'quux' => 'baz'];
echo
json_encode(new ArrayValue($array), JSON_PRETTY_PRINT);
?>

O exemplo acima produzirá:

{
    "foo": "bar",
    "quux": "baz"
}

Exemplo #3 Exemplo de JsonSerializable::jsonSerialize() retornando um int

<?php
class IntegerValue implements JsonSerializable {
private
$number;
public function
__construct($number) {
$this->number = (int) $number;
}

public function
jsonSerialize(): mixed {
return
$this->number;
}
}

echo
json_encode(new IntegerValue(1), JSON_PRETTY_PRINT);
?>

O exemplo acima produzirá:

1

Exemplo #4 Exemplo de JsonSerializable::jsonSerialize() retornando uma string

<?php
class StringValue implements JsonSerializable {
private
$string;
public function
__construct($string) {
$this->string = (string) $string;
}

public function
jsonSerialize(): mixed {
return
$this->string;
}
}

echo
json_encode(new StringValue('Hello!'), JSON_PRETTY_PRINT);
?>

O exemplo acima produzirá:

"Hello!"