PHP code example of kingson-de / marshal-json-serializer

1. Go to this page and download the library: Download kingson-de/marshal-json-serializer 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/ */

    

kingson-de / marshal-json-serializer example snippets




use KingsonDe\Marshal\Data\Item;
use KingsonDe\Marshal\MarshalJson;

$json = MarshalJson::serialize(new Item($mapper, $model));
// or
$json = MarshalJson::serializeItem($mapper, $model);
// or
$json = MarshalJson::serializeItemCallable(function (User $user) {
    return [
        'username'  => $user->getUsername(),
        'email'     => $user->getEmail(),
        'birthday'  => $user->getBirthday()->format('Y-m-d'),
        'followers' => count($user->getFollowers()),
    ];
}, $user);
// or
$json = MarshalJson::serializeCollection($mapper, $modelCollection);
// or 
$json = MarshalJson::serializeCollectionCallable(function (User $user) {
    return [
        'username'  => $user->getUsername(),
        'email'     => $user->getEmail(),
        'birthday'  => $user->getBirthday()->format('Y-m-d'),
        'followers' => count($user->getFollowers()),
    ];
}, $userCollection);



use KingsonDe\Marshal\AbstractObjectMapper;
use KingsonDe\Marshal\Data\FlexibleData;

class UserIdMapper extends AbstractObjectMapper {

    public function map(FlexibleData $flexibleData, ...$additionalData) {
        return $flexibleData->get('id');
    }
}



use KingsonDe\Marshal\MarshalJson;

$json = '{"id": 123}';

$id = MarshalJson::deserializeJson($json, new UserIdMapper());



use KingsonDe\Marshal\MarshalJson;

$id = MarshalJson::deserializeJsonCallable($json, function (FlexibleData $flexibleData) {
    return $flexibleData['id'];
});



use KingsonDe\Marshal\Data\FlexibleData;
use KingsonDe\Marshal\MarshalJson;

$json = '{"name": "John Doe"}';

$flexibleData = new FlexibleData(MarshalJson::deserializeJsonToData($json));
$flexibleData['name'] = 'Jane Doe';

$modifiedJson = MarshalJson::serialize($flexibleData);