Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/sanmai/json-serializer
Flexible JSON Serializer
https://github.com/sanmai/json-serializer
json php serializer
Last synced: 21 days ago
JSON representation
Flexible JSON Serializer
- Host: GitHub
- URL: https://github.com/sanmai/json-serializer
- Owner: sanmai
- License: mit
- Created: 2020-09-29T05:58:43.000Z (about 4 years ago)
- Default Branch: main
- Last Pushed: 2024-02-17T11:02:01.000Z (10 months ago)
- Last Synced: 2024-11-18T09:57:02.384Z (about 1 month ago)
- Topics: json, php, serializer
- Language: PHP
- Homepage:
- Size: 78.1 KB
- Stars: 1
- Watchers: 3
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- Contributing: CONTRIBUTING.md
- License: LICENSE
- Code of conduct: CODE_OF_CONDUCT.md
Awesome Lists containing this project
README
# Flexible JSON Serializer
[![Latest Stable Version](https://poser.pugx.org/sanmai/json-serializer/v/stable)](https://packagist.org/packages/sanmai/json-serializer)
[![Coverage Status](https://coveralls.io/repos/github/sanmai/json-serializer/badge.svg?branch=master)](https://coveralls.io/github/sanmai/json-serializer?branch=master)This library is a thin wrapper around [jms/serializer](https://github.com/schmittjoh/serializer).
The purpose of this library is to make simpler deserialization/serialization of objects and, specifically, of arrays of objects, and scalar values. All you need is to follow a simple protocol.
### ItemList
JMS Serializer supports deserializing arrays out of the box, but it is ever so slightly complicated since a user must specify a type in a full form, as in `array`, all the while returned deserialized value will be a plain array. This library abstracts away this extra complexity by providing a two-method protocol instead.
For example, deserialising this object:
```php
use JSONSerializer\Contracts\ItemList;class ItemListExample implements ItemList
{
/** @var ItemExample[] */
public $items = [];public static function getListType(): string
{
return ItemExample::class;
}public static function withList(array $list)
{
$itemList = new self();
$itemList->items = $list;return $itemList;
}
}
```From a JSON array:
```json
[
{"name": "foo"},
{"name": "bar"}
]
```With an all-familiar method:
```php
use JSONSerializer\Serializer;$serializer = new Serializer();
$result = $serializer->deserialize($json, ItemListExample::class);
```Will leave an instance of `ItemListExample` in `$result` with `$result->items` filled with two items as in the source array.
### ScalarValue
There's a similar convenience interface called `ScalarValue` to aid with unserializing wrapped primitive scalar values.
```php
use JSONSerializer\Contracts\ScalarValue;class ScalarValueExample implements ScalarValue
{
/** @var int */
public $value;public static function withValue($value)
{
$item = new self();
$item->value = $value;return $item;
}public static function getType(): string
{
return 'int';
}
}
```