PHP code example of baldie81 / json-marshaler

1. Go to this page and download the library: Download baldie81/json-marshaler 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/ */

    

baldie81 / json-marshaler example snippets


use Baldie81\JsonMarshaler\JsonMarshal;

readonly class User
{
    public function __construct(
        public int $id,
        public string $name,
        public string $email,
    ) {}
}

$user = new User(1, 'Jane Doe', '[email protected]');

echo JsonMarshal::to($user);

$json = '{"id": 1, "name": "Jane Doe", "email": "[email protected]"}';

$user = JsonMarshal::from($json, User::class);

echo $user->name; // "Jane Doe"

use Baldie81\JsonMarshaler\Attributes\JsonProperty;

readonly class Product
{
    public function __construct(
        public int $id,
        #[JsonProperty('product_name')]
        public string $productName,
        #[JsonProperty('unit_price')]
        public float $unitPrice,
    ) {}
}

$json = '{"id": 1, "product_name": "Widget", "unit_price": 9.99}';

$product = JsonMarshal::from($json, Product::class);
echo $product->productName; // "Widget"

echo JsonMarshal::to($product);
// {"id": 1, "product_name": "Widget", "unit_price": 9.99}

readonly class Profile
{
    public function __construct(
        #[JsonProperty('first_name')]
        public string $firstName,
        #[JsonProperty('middle_name', omitEmpty: true)]
        public ?string $middleName = null,
        #[JsonProperty('tags', omitEmpty: true)]
        public array $tags = [],
    ) {}
}

$profile = new Profile(firstName: 'Alice');

echo JsonMarshal::to($profile);
// {"first_name": "Alice"}
// — middle_name and tags are omitted

$profile = new Profile(firstName: 'Alice', middleName: 'B', tags: ['admin']);

echo JsonMarshal::to($profile);
// {"first_name": "Alice", "middle_name": "B", "tags": ["admin"]}

readonly class Credentials
{
    public function __construct(
        #[JsonProperty('username')]
        public string $username,
        #[JsonProperty('password', sensitive: true)]
        public string $password,
    ) {}
}

$creds = new Credentials(username: 'admin', password: 's3cret!');

echo JsonMarshal::to($creds);
// {"username": "admin", "password": "****"}

echo $creds->password; // "s3cret!" — original value is untouched

readonly class Address
{
    public function __construct(
        public string $street,
        public string $city,
        #[JsonProperty('zip_code')]
        public string $zipCode,
    ) {}
}

readonly class Customer
{
    public function __construct(
        public int $id,
        public string $name,
        public Address $address,
    ) {}
}

$json = '{
    "id": 1,
    "name": "Jane Doe",
    "address": {
        "street": "123 Main St",
        "city": "Springfield",
        "zip_code": "62704"
    }
}';

$customer = JsonMarshal::from($json, Customer::class);
echo $customer->address->city; // "Springfield"

use Baldie81\JsonMarshaler\Attributes\JsonList;

readonly class OrderItem
{
    public function __construct(
        #[JsonProperty('product_name')]
        public string $productName,
        public int $quantity,
        public float $price,
    ) {}
}

readonly class Order
{
    public function __construct(
        public int $id,
        #[JsonList(OrderItem::class)]
        public array $items,
    ) {}
}

$json = '{
    "id": 42,
    "items": [
        {"product_name": "Widget", "quantity": 2, "price": 9.99},
        {"product_name": "Gadget", "quantity": 1, "price": 24.99}
    ]
}';

$order = JsonMarshal::from($json, Order::class);
echo $order->items[0]->productName; // "Widget"

use Baldie81\JsonMarshaler\Traits\SelfHydrating;

readonly class User
{
    use SelfHydrating;

    public function __construct(
        public int $id,
        public string $name,
        public string $email,
    ) {}
}

$user = User::fromJson('{"id": 1, "name": "Jane", "email": "[email protected]"}');
echo $user->toJson();

use Baldie81\JsonMarshaler\Validators\{NotEmpty, MinLength, MaxLength, Pattern, Range, Url, InList};

readonly class Product
{
    public function __construct(
        #[NotEmpty]
        public string $name,
        #[MinLength(3)]
        #[MaxLength(20)]
        #[Pattern('/^[A-Z0-9\-]+$/')]
        public string $sku,
        #[Range(min: 0.01, max: 99999.99)]
        public float $price,
        #[Url]
        public string $website,
        #[InList('active', 'draft', 'archived')]
        public string $status,
    ) {}
}

$json = '{"name": "", "sku": "AB", "price": 10, "website": "https://example.com", "status": "active"}';

JsonMarshal::from($json, Product::class);
// InvalidArgumentException: Field 'name' must not be empty.

use Baldie81\JsonMarshaler\Contracts\ValidatorInterface;
use Attribute;

#[Attribute(Attribute::TARGET_PROPERTY)]
readonly class Lowercase implements ValidatorInterface
{
    public function isValid(mixed $value): bool
    {
        return is_string($value) && $value === strtolower($value);
    }

    public function getErrorMessage(string $field): string
    {
        return "Field '{$field}' must be lowercase.";
    }
}

readonly class Tag
{
    public function __construct(
        #[Lowercase]
        public string $slug,
    ) {}
}

readonly class Emoji
{
    use SelfHydrating;

    public function __construct(
        #[NotEmpty]
        public string $name,
        public string $category,
        public string $group,
        public array $htmlCode,
        public array $unicode,
    ) {}
}

// Consuming a real API — https://emojihub.yurace.pro/api/random
$response = file_get_contents('https://emojihub.yurace.pro/api/random');
$emoji = Emoji::fromJson($response);

echo $emoji->name;        // "old man, type-5"
echo $emoji->category;    // "smileys and people"
echo $emoji->group;       // "person"
echo $emoji->htmlCode[0]; // "&#128116;"

// In a Laravel/Symfony/Slim controller
$customer = Customer::fromJson($request->getContent()); // validated on the way in

// ... business logic ...

return new JsonResponse(
    json_decode(JsonMarshal::to($customer), true),
    200
);

use Baldie81\JsonMarshaler\Attributes\{JsonProperty, JsonList};
use Baldie81\JsonMarshaler\Traits\SelfHydrating;
use Baldie81\JsonMarshaler\Validators\{Email, NotEmpty, Range};

readonly class Address
{
    public function __construct(
        #[NotEmpty]
        public string $street,
        #[NotEmpty]
        public string $city,
        #[JsonProperty('zip_code')]
        public string $zipCode,
    ) {}
}

readonly class OrderItem
{
    public function __construct(
        #[JsonProperty('product_name')]
        #[NotEmpty]
        public string $productName,
        #[Range(min: 1, max: 1000)]
        public int $quantity,
        public float $price,
    ) {}
}

readonly class Customer
{
    use SelfHydrating;

    public function __construct(
        public int $id,
        #[JsonProperty('full_name')]
        #[NotEmpty]
        public string $fullName,
        #[Email]
        public string $email,
        public Address $address,
        #[JsonList(OrderItem::class)]
        public array $orders = [],
    ) {}
}

$json = '{
    "id": 1,
    "full_name": "Jane Doe",
    "email": "[email protected]",
    "address": {
        "street": "123 Main St",
        "city": "Springfield",
        "zip_code": "62704"
    },
    "orders": [
        {"product_name": "Widget", "quantity": 3, "price": 9.99},
        {"product_name": "Gadget", "quantity": 1, "price": 24.99}
    ]
}';

$customer = Customer::fromJson($json);

echo $customer->fullName;           // "Jane Doe"
echo $customer->address->city;      // "Springfield"
echo $customer->orders[0]->productName; // "Widget"
echo $customer->toJson();           // Back to JSON