PHP Function Reference

PHP JsonSerializable - jsonSerialize() Method



The PHP JsonSerializable::jsonSerialize() method serializes the object to a value that can be serialized natively by json_encode().

Syntax

public JsonSerializable::jsonSerialize()

Parameters

No parameter is required.

Return Value

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

Example: JsonSerializable::jsonSerialize() example returning an array

The example below demonstrates how to use this method to return an array.

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

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

$arr = array(10, 20, 30);
echo json_encode(new ArrayValue($arr), JSON_PRETTY_PRINT);
?>

The output of the above code will be:

[
    10,
    20,
    30
]

Example: JsonSerializable::jsonSerialize() example returning an associative array

The example below demonstrates how to use this method to return an associative array.

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

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

$arr = array(10 => "Red", 
             20 => "Green", 
             30 => "Blue");
echo json_encode(new ArrayValue($arr), JSON_PRETTY_PRINT);
?>

The output of the above code will be:

{
    "10": "Red",
    "20": "Green",
    "30": "Blue"
}

Example: JsonSerializable::jsonSerialize() example returning an int

The example below demonstrates how to use this method to return an integer.

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

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

$num = 1000;
echo json_encode(new IntegerValue($num), JSON_PRETTY_PRINT);
?>

The output of the above code will be:

1000

Example: JsonSerializable::jsonSerialize() example returning a string

The example below demonstrates how to use this method to return a string.

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

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

$str = "Hello World!";
echo json_encode(new StringValue($str), JSON_PRETTY_PRINT);
?>

The output of the above code will be:

"Hello World!"

❮ PHP JSON Reference