PHP code example of ddn / jsonobject
1. Go to this page and download the library: Download ddn/jsonobject library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
ddn / jsonobject example snippets
class User extends JsonObject {
const ATTRIBUTES = [
'id' => 'int',
'name' => 'str',
'age' => 'int',
'emails' => 'list[str]',
'address?' => 'Address',
];
}
class Address extends JsonObject {
const ATTRIBUTES = [
'street' => 'str',
'number' => 'int',
'city' => 'str',
'country' => 'str',
];
}
$user = User::fromObject(json_decode($json_text_definition));
echo($user->name);
class User extends JsonObject {
const ATTRIBUTES = [
'id' => 'int',
'name' => 'str',
'age' => 'int',
'emails' => 'list[str]',
'address?' => 'Address',
];
public function isAdult() {
return $this->age >= 18;
}
}
class User extends JsonObject {
const ATTRIBUTES = [
"name" => "str",
"age" => "int",
];
}
(...)
$user = User::fromArray([ "name" => "John" ]);
class User extends JsonObject {
const ATTRIBUTES = [
"name" => "str",
"age" => "int",
"birthDate?" => "str"
];
}
$user = new User();
echo((string)$user);
class Vehicle extends JsonObject {
const ATTRIBUTES = [
"brand" => "str",
"color" => "str"
]
}
class Car extends Vehicle {
const ATTRIBUTES = [
"wheels" => "int"
]
}
class Boat extends Vehicle {
const ATTRIBUTES = [
"length" => "float"
]
}
$json = file_get_contents("car.json");
$vehicle = Vehicle::fromArray((array)json_decode($json, true));
$car = new Car(brand: "BMW", color: "black", wheels: 4);
$car = new Car([ "brand" => "BMW", "color" => "black", "wheels" => 4]);
class User extends JsonObject {
const ATTRIBUTES = [
'id' => 'int',
'name' => 'str',
'age' => 'int',
'emails' => 'list[str]',
'address?' => 'Address',
'sex?' => 'str'
];
public $sex = "not revealed";
}
class User extends JsonObject {
const ATTRIBUTES = [
'id' => 'int',
'name' => 'str',
'age' => 'int',
'emails' => 'list[str]',
'address?' => 'Address',
'sex?' => [ 'str', 'not revealed' ]
];
}
class User extends JsonObject {
const ATTRIBUTE = [
...
'birthDay?' => [ 'str', 'computeBirthDate' ]
]
function computeBirthDate() {
$now = new DateTime();
$now->sub(DateInterval::createFromDateString("{$this->age} years"));
return $now->format("Y-m-d");
}
}
$myobject = JsonObject::parse_typed_value("list[str]", [ "my", "name", "is", "John" ]);