JsonSerializable::jsonSerialize

(PHP 5 >= 5.4.0)

JsonSerializable::jsonSerializeSpecify data which should be serialized to JSON

Beschreibung

abstract public mixed JsonSerializable::jsonSerialize ( void )

Serializes the object to a value that can be serialized natively by json_encode().

Parameter-Liste

Diese Funktion hat keine Parameter.

R├╝ckgabewerte

Returns data which can be serialized by json_encode(), which is a value of any type other than a resource.

Beispiele

Beispiel #1 JsonSerializable::jsonSerialize() example returning an array

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

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

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

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

[
    1,
    2,
    3
]

Beispiel #2 JsonSerializable::jsonSerialize() example returning an associative array

<?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);
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

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

Beispiel #3 JsonSerializable::jsonSerialize() example returning an 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);
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

1

Beispiel #4 JsonSerializable::jsonSerialize() example returning a 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('Hello!'), JSON_PRETTY_PRINT);
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

"Hello!"

add a note add a note

User Contributed Notes 2 notes

up
16
benkuhl at gmail dot com
1 year 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
-1
simonsimcity at gmail dot com
1 month ago
You can't throw exceptions in here. If you do, you'll get an exception with the message "Failed calling FooClass::jsonSerialize()" and the stacktrace will start at where you called the json_encode() method.

Here's a code-example:

class Foo implements JsonSerializable {
    private $triggerError = true;

    public function jsonSerialize()
    {
        if ($this->triggerError) {
            throw new RuntimeException("It failed!");
        }

        return (array)$this;
    }
}

// Will throw an exception like new Exception("Failed calling Foo::jsonSerialize()")
json_encode(new Foo());
To Top