JsonSerializable::jsonSerialize

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

JsonSerializable::jsonSerialize β€” Π—Π°Π΄Π°Ρ‘Ρ‚ Π΄Π°Π½Π½Ρ‹Π΅, ΠΊΠΎΡ‚ΠΎΡ€Ρ‹Π΅ Π΄ΠΎΠ»ΠΆΠ½Ρ‹ Π±Ρ‹Ρ‚ΡŒ сСриализованы Π² JSON

ОписаниС

public function JsonSerializable::jsonSerialize(): mixed

Π‘Π΅Ρ€ΠΈΠ°Π»ΠΈΠ·ΡƒΠ΅Ρ‚ ΠΎΠ±ΡŠΠ΅ΠΊΡ‚ Π² Π·Π½Π°Ρ‡Π΅Π½ΠΈΠ΅, ΠΊΠΎΡ‚ΠΎΡ€ΠΎΠ΅ ΠΈΠ·Π½Π°Ρ‡Π°Π»ΡŒΠ½ΠΎ ΠΌΠΎΠΆΠ΅Ρ‚ Π±Ρ‹Ρ‚ΡŒ сСриализовано Ρ„ΡƒΠ½ΠΊΡ†ΠΈΠ΅ΠΉ json_encode().

Бписок ΠΏΠ°Ρ€Π°ΠΌΠ΅Ρ‚Ρ€ΠΎΠ²

Π‘ΠΈΠ³Π½Π°Ρ‚ΡƒΡ€Π° Ρ„ΡƒΠ½ΠΊΡ†ΠΈΠΈ Π½Π΅ содСрТит ΠΏΠ°Ρ€Π°ΠΌΠ΅Ρ‚Ρ€ΠΎΠ².

Π’ΠΎΠ·Π²Ρ€Π°Ρ‰Π°Π΅ΠΌΡ‹Π΅ значСния

Π’ΠΎΠ·Π²Ρ€Π°Ρ‰Π°Π΅Ρ‚ Π΄Π°Π½Π½Ρ‹Π΅, ΠΊΠΎΡ‚ΠΎΡ€Ρ‹Π΅ ΠΌΠΎΠ³ΡƒΡ‚ Π±Ρ‹Ρ‚ΡŒ сСриализованы json_encode(), ΠΊΠΎΡ‚ΠΎΡ€Ρ‹Π΅ ΡΠ²Π»ΡΡŽΡ‚ΡΡ Π·Π½Π°Ρ‡Π΅Π½ΠΈΠ΅ΠΌ любого Ρ‚ΠΈΠΏΠ°, ΠΊΡ€ΠΎΠΌΠ΅ resource.

ΠŸΡ€ΠΈΠΌΠ΅Ρ€Ρ‹

ΠŸΡ€ΠΈΠΌΠ΅Ρ€ #1 ΠŸΡ€ΠΈΠΌΠ΅Ρ€ использования JsonSerializable::jsonSerialize(), Π²ΠΎΠ·Π²Ρ€Π°Ρ‰Π°ΡŽΡ‰ΠΈΠΉ массив (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);
?>

Π Π΅Π·ΡƒΠ»ΡŒΡ‚Π°Ρ‚ выполнСния ΠΏΡ€ΠΈΠ²Π΅Π΄Ρ‘Π½Π½ΠΎΠ³ΠΎ ΠΏΡ€ΠΈΠΌΠ΅Ρ€Π°:

[
    1,
    2,
    3
]

ΠŸΡ€ΠΈΠΌΠ΅Ρ€ #2 ΠŸΡ€ΠΈΠΌΠ΅Ρ€ использования JsonSerializable::jsonSerialize(), Π²ΠΎΠ·Π²Ρ€Π°Ρ‰Π°ΡŽΡ‰ΠΈΠΉ ассоциативный массив (array)

<?php

class ArrayValue implements JsonSerializable {
private
$array;
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);
?>

Π Π΅Π·ΡƒΠ»ΡŒΡ‚Π°Ρ‚ выполнСния ΠΏΡ€ΠΈΠ²Π΅Π΄Ρ‘Π½Π½ΠΎΠ³ΠΎ ΠΏΡ€ΠΈΠΌΠ΅Ρ€Π°:

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

ΠŸΡ€ΠΈΠΌΠ΅Ρ€ #3 ΠŸΡ€ΠΈΠΌΠ΅Ρ€ использования JsonSerializable::jsonSerialize(), Π²ΠΎΠ·Π²Ρ€Π°Ρ‰Π°ΡŽΡ‰ΠΈΠΉ Ρ†Π΅Π»ΠΎΠ΅ Π·Π½Π°Ρ‡Π΅Π½ΠΈΠ΅ (int)

<?php

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

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

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

Π Π΅Π·ΡƒΠ»ΡŒΡ‚Π°Ρ‚ выполнСния ΠΏΡ€ΠΈΠ²Π΅Π΄Ρ‘Π½Π½ΠΎΠ³ΠΎ ΠΏΡ€ΠΈΠΌΠ΅Ρ€Π°:

1

ΠŸΡ€ΠΈΠΌΠ΅Ρ€ #4 ΠŸΡ€ΠΈΠΌΠ΅Ρ€ использования JsonSerializable::jsonSerialize(), Π²ΠΎΠ·Π²Ρ€Π°Ρ‰Π°ΡŽΡ‰ΠΈΠΉ строку (string)

<?php

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

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

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

Π Π΅Π·ΡƒΠ»ΡŒΡ‚Π°Ρ‚ выполнСния ΠΏΡ€ΠΈΠ²Π΅Π΄Ρ‘Π½Π½ΠΎΠ³ΠΎ ΠΏΡ€ΠΈΠΌΠ΅Ρ€Π°:

"Hello!"
οΌ‹Π”ΠΎΠ±Π°Π²ΠΈΡ‚ΡŒ

ΠŸΡ€ΠΈΠΌΠ΅Ρ‡Π°Π½ΠΈΡ ΠΏΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚Π΅Π»Π΅ΠΉ 4 notes

up
79
benkuhl at gmail dot com ΒΆ
13 years ago
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...

<?php

date_default_timezone_set('America/Los_Angeles');

class Fruit implements JsonSerializable {
    public
        $type = 'Apple',
        $lastEaten = null;

    public function __construct() {
        $this->lastEaten = new DateTime();
    }

    public function jsonSerialize() {
        return [
            'type' => $this->type,
            'lastEaten' => $this->lastEaten->format(DateTime::ISO8601)
        ];
    }
}
echo json_encode(new Fruit()); //which outputs: {"type":"Apple","lastEaten":"2013-01-31T11:17:07-0500"}

?>
up
20
tomasz dot darmetko at gmail dot com ΒΆ
8 years ago
Nested json serializable objects will be serialized recursively. No need to call ->jsonSerialize() on your own. It is especially useful in collections.

<?php

class NestedSerializable implements \JsonSerializable
{

    private $serializable;

    public function __construct($serializable)
    {
        $this->serializable = $serializable;
    }

    public function jsonSerialize()
    {
        return [
            'serialized' => $this->serializable
        ];
    }

}

class SerializableCollection implements \JsonSerializable {

    private $elements;

    public function __construct(array $elements)
    {
        $this->elements = $elements;
    }

    public function jsonSerialize()
    {
        return $this->elements;
    }

}

// Outputs: [{"serialized":null},{"serialized":null},{"serialized":{"serialized":null}}]
echo json_encode(
    new SerializableCollection([
        new NestedSerializable(null),
        new NestedSerializable(null),
        new NestedSerializable(new NestedSerializable(null))
    ])
);

?>
up
5
info at digistratum dot com ΒΆ
9 years ago
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:

<?php
class jsontest implements JsonSerializable {
        function __construct($value) { $this->value = $value; }
        function jsonSerialize() { return $this->value; }
}

print "Null -> " . json_encode(new jsontest(null)) . "\n";
print "Array -> " . json_encode(new jsontest(Array(1,2,3))) . "\n";
print "Assoc. -> " . json_encode(new jsontest(Array('a'=>1,'b'=>3,'c'=>4))) . "\n";
print "Int -> " . json_encode(new jsontest(5)) . "\n";
print "String -> " . json_encode(new jsontest('Hello, World!')) . "\n";
print "Object -> " . json_encode(new jsontest((object) Array('a'=>1,'b'=>3,'c'=>4))) . "\n";
?>

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}
up
0
david at vanlaatum dot id dot au ΒΆ
11 years ago
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