Skip to content

Instantly share code, notes, and snippets.

@balthild
Last active February 19, 2024 18:18
Show Gist options
  • Save balthild/37f72106f775e6b25417d4e778a38d5b to your computer and use it in GitHub Desktop.
Save balthild/37f72106f775e6b25417d4e778a38d5b to your computer and use it in GitHub Desktop.
MWE for Crell/Serde#52

Execute:

composer install
php index.php

Output:

object(MyList)#35 (0) {
  ["items"]=>
  uninitialized(array)
}
object(MyList)#36 (0) {
  ["items"]=>
  uninitialized(array)
}
{
"name": "balthild/mwe",
"require": {
"crell/serde": "^1.1"
},
"authors": []
}
<?php
use Crell\Serde\SerdeCommon;
require __DIR__ . '/vendor/autoload.php';
readonly class MyList {
#[SequenceField(arrayType: MyItem::class)]
public array $items;
}
readonly class MyItem {
public int $id;
}
$serde = new SerdeCommon();
// Trying JSON
$json = '[
{ "id": 1 },
{ "id": 2 }
]';
$obj = $serde->deserialize($json, from: 'json', to: MyList::class);
var_dump($obj);
// Trying PHP array
$array = [
[ "id" => 1 ],
[ "id" => 2 ]
];
$obj2 = $serde->deserialize($array, from: 'array', to: MyList::class);
var_dump($obj2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment