AthenaeumAthenaeum
Packages
  • next
  • current
  • v9.x
  • v8.x
  • v7.x
  • v6.x
  • v5.x
  • v4.x
  • v3.x
  • v2.x
  • v1.x
Changelog
GitHub
Packages
  • next
  • current
  • v9.x
  • v8.x
  • v7.x
  • v6.x
  • v5.x
  • v4.x
  • v3.x
  • v2.x
  • v1.x
Changelog
GitHub
  • Version 3.x

    • How to install
  • Config

    • Configuration Loader
  • Container

    • IoC Service Container
  • Dto

    • Data Transfer Object (DTO)
    • Create Interface
    • Implement DTO
    • Property overloading
    • Populate
    • Json
    • Nested DTOs
    • Array DTO
  • Http

    • Introduction
    • Http Clients
  • Properties

    • Properties Overload
  • Support

    • Support Introduction
    • Laravel Aware Of Helpers
    • Aware Of Properties
    • Aware-Of Component Generator
  • Testing

    • Testing Introduction
    • Laravel
    • Test Cases
    • Traits
  • Utils

    • Populate
    • Json
You are viewing documentation for an outdated version. It is no longer supported!

Json

All DTOs are Json serializable, meaning that they inherit from the JsonSerializable interface. This means that when using json_encode(), the DTO automatically ensures that its properties are serializable by the encoding method.

$person = new Person([
    'name' => 'Rian Dou',
    'age' => 29
]);

echo json_encode($person);

The above example will output the following Json string;

{
    "name":"Rian Dou",
    "age":29
}

toJson()

You can also perform json serialization directly on the DTO, by invoking the toJson() method.

$person = new Person([
    'name' => 'Rian Dou',
    'age' => 29
]);

echo $person->toJson(); // The same as invoking json_encode($person);

Populate from Json

To populate a DTO directly from a Json string, use the fromJson() method.

$json = '{"name":"Miss Mossie Wehner Sr.","age":28}';

$person = Person::fromJson($json);

echo $person->name; // Miss Mossie Wehner Sr.

Note

fromJson() returns a new DTO instance.

Edit page
Last Updated: 08/02/2020, 09:56
Contributors: Alin Eugen Deac
Prev
Populate
Next
Nested DTOs