PHP code example of andreypostal / json-handler-php
1. Go to this page and download the library: Download andreypostal/json-handler-php 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/ */
andreypostal / json-handler-php example snippets
use \Andrey\JsonHandler\Attributes\JsonItemAttribute;
// { "id": 123, "name": "my name" }
class MyObject {
#[JsonItemAttribute]
public int $id;
#[JsonItemAttribute]
public name $name;
}
use \Andrey\JsonHandler\Attributes\JsonObjectAttribute;
// { "id": 123, "name": "my name" }
#[JsonObjectAttribute]
class MyObject {
public int $id;
public string $name;
}
use \Andrey\JsonHandler\Attributes\JsonObjectAttribute;
use \Andrey\JsonHandler\Attributes\JsonItemAttribute;
// { "id": 123, "custom_name": "my name" }
#[JsonObjectAttribute]
class MyObject {
public int $id;
#[JsonItemAttribute(key: 'custom_name')]
public string $name;
}
use \Andrey\JsonHandler\Attributes\JsonItemAttribute;
// { "id": 123 }
class MyObject {
#[JsonItemAttribute]
public int $id;
public int $myAppGeneratesIt;
}
use \Andrey\JsonHandler\Attributes\JsonItemAttribute;
// { "id": 123 } or { "id": 123, "name": "my name" }
class MyObject {
#[JsonItemAttribute(
use \Andrey\JsonHandler\Attributes\JsonItemAttribute;
// { "customer_name": "the customer name" }
class MyObject {
#[JsonItemAttribute(key: 'customer_name')]
public string $name;
}
use \Andrey\JsonHandler\JsonItemAttribute;
use \MyNamespace\MyOtherObj;
// { "list": [ { "key": "value" } ] }
class MyObject {
/** @var MyOtherObj[] */
#[JsonItemAttribute(type: MyOtherObj::class)]
public array $list;
}
use \Andrey\JsonHandler\JsonHandler;
use \MyNamespace\MyObject;
$handler = new JsonHandler();
$myObject = new MyObject();
// This parses the json string and hydrates the original object, modifying it
$handler->hydrateObject($jsonString, $myObject);
// If you don't want to modify the original object you can use the immutable hydration
$hydratedObject = $handler->hydrateObjectImmutable($jsonString, $myObject);
// You can also use an array to hydrate the object
$handler->hydrateObject($jsonArr, $myObject);
// And to fetch the information as an array you can just serialize it using the handler.
// This allows you to easily implement the JsonSerializable interface in your object.
$arr = $handler->serialize($myObject);
// The json handler also provides the methods to decode and encode
$jsonString = JsonHandler::Encode($arr);
$jsonArr = JsonHandler::Decode($jsonString);
composer
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.