Marshal JSON is serializing / marshalling data structures to JSON. It is also deserializing / unmarshalling JSON back to the data structures.
Marshal JSON is serializing / marshalling) data structures to JSON. It is also deserializing / unmarshalling JSON back to the data structures.
Easiest way to install the library is via composer:
composer require kingson-de/marshal-json-serializer
The following PHP versions are supported:
Just run:
composer test
Or without code coverage:
composer quicktest
Please check the Marshal Serializer README for more information.
The library provides several static methods to create your JSON data once you defined the data structures.
<?php
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);
To transform JSON back to your structure use Marshal’s deserialize functions.
You need a class extending the AbstractObjectMapper which will be passed to the deserializeJson function.
When using FlexibleData’s get function it will throw an OutOfBoundsException if the key does not exist.
If an exception is not needed the find function can be used which will return a custom default value in that case.
<?php
use KingsonDe\Marshal\AbstractObjectMapper;
use KingsonDe\Marshal\Data\FlexibleData;
class UserIdMapper extends AbstractObjectMapper {
public function map(FlexibleData $flexibleData, ...$additionalData) {
return $flexibleData->get('id');
}
}
<?php
use KingsonDe\Marshal\MarshalJson;
$json = '{"id": 123}';
$id = MarshalJson::deserializeJson($json, new UserIdMapper());
Another option would be to use the deserializeCallable function.
<?php
use KingsonDe\Marshal\MarshalJson;
$id = MarshalJson::deserializeJsonCallable($json, function (FlexibleData $flexibleData) {
return $flexibleData['id'];
});
An easy way to modify existing JSON is to use FlexibleData.
Here is an example:
<?php
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);
This project is released under the terms of the Apache 2.0 license.