Festi De/Serialization

Deserializes JSON (or a pre-decoded PHP array) into a typed PHP object driven by the #[JsonProperty] attribute.

Requirements: PHP 8.1+, ext-json. No runtime dependencies.

Upgrading

Values of a wrong type and missing values name their key

  • A value that the type of its key cannot take throws core\json\InvalidValueException. Before, a text that is not a number, for example "five", went into an int property or setter as 0, a number with a fraction ("5.5", 5.5, "1e3") went in as its whole part, and another value of a wrong type gave a PHP TypeError. An empty text and null still give 0 for an int (or null when the type is nullable).
  • null for a nested object whose type is nullable gives null, as an absent key does.
  • A missing value of a constructor parameter that has no default throws core\json\MissingValueException. Before, the parameter got null, and the constructor gave a TypeError that named the parameter and not the key. A nullable promoted parameter with no default still gets null, unless #[JsonProperty] marks its key as required: such a key is refused when it is absent, as before, also when it has a default.
  • The message for a missing constructor value is Undefined required value for key <key>, the same as for a property. Before, it was Undefined constructor parameters: <key>.
  • The two exceptions extend JsonPropertyException, thus a catch (JsonPropertyException ...) still catches them. Each has getKey(), the key of the data.
  • A constructor parameter gets the value of its key once. Its promoted property is not set a second time, thus a readonly promoted property works. An empty text for a nullable promoted string is still null; PHP converts or refuses each other value of a constructor parameter, as before.
  • A constructor parameter that is not promoted gets the value of its #[JsonProperty] key.
  • A TypeError from the code inside a constructor or a setter stays a TypeError: only a value that the parameter itself refuses becomes an InvalidValueException.

Native types and PHP 8.1

The package requires PHP 8.1 or later. PHP 8.0 is not supported. If your project uses PHP 8.0, keep the earlier version of the package or upgrade PHP to 8.1 or later.

Since PHP 8.1, reflection can set a private or protected property without ReflectionProperty::setAccessible(). Thus the package does not call setAccessible(). On PHP 8.5 this call causes an E_DEPRECATED message.

These public methods now have native types:

Method New signature
Deserialize::toObject() toObject(string $json, string $className): object
Deserialize::toArrayObject() toArrayObject(array $data, string $className): object
DeserializeMapper::map() map(array $data): object
DeserializeMapper::mapProperty() mapProperty(object &$object, string $key, mixed $value): void
DeserializeMapper::createObject() createObject(mixed ...$arguments): object

This is a break in two cases:

  • A subclass that overrides one of these methods without the same types causes a fatal error. Add the types to the method of the subclass.
  • A call of mapProperty() with a target that is not an object causes a TypeError.

The files of the package declare strict_types=1. The conversion of a scalar value does not change: a numeric string such as "5" still goes into an int property, constructor parameter or setter parameter.

Quick start

use core\json\Deserialize;
use core\json\JsonProperty;

class UserProfile
{
    #[JsonProperty("first_name")]
    private string $_firstName;

    #[JsonProperty("age")]
    private int $_age;

    public function getFirstName(): string
    {
        return $this->_firstName;
    }

    public function getAge(): int
    {
        return $this->_age;
    }
}

$json = '{"first_name": "Alice", "age": 30}';

$profile = Deserialize::toObject($json, UserProfile::class);
// $profile->getFirstName() === "Alice"

The #[JsonProperty] attribute

#[JsonProperty(name: string = '', isRequired: bool = false, description: string = '')]
Argument Default Meaning
name '' The JSON key to read. When empty, the reflected property or parameter name is used as-is. On setter methods a name is required — omitting it throws JsonPropertyException.
isRequired false When true, deserialization throws JsonPropertyException if the key is missing from the input.
description '' Free-form metadata for downstream schema generators. Has no effect on deserialization.

Properties without #[JsonProperty] are ignored unless the JSON key happens to match the property name exactly and you add the attribute without a name.

Three injection patterns

A single class can mix all three patterns. Constructor parameters run first, then property injectors, then method injectors.

1. Property injection

Annotate the property directly. Public, protected, and private properties all work.

class Article
{
    #[JsonProperty("title")]
    private string $_title;

    // Attribute without a name → uses the property name "score" as the JSON key
    #[JsonProperty]
    protected int $score;

    // No attribute → this property is skipped during deserialization
    public string $ignored;
}

$article = Deserialize::toObject('{"title":"Hello","score":42}', Article::class);

2. Constructor injection

Use promoted or typed constructor parameters when the class requires immutability or a specific construction order. Constructor parameters without a default value are automatically treated as required: a missing key throws MissingValueException, except for a nullable promoted parameter, which gets null. An absent key with a default gives the default. A key that #[JsonProperty] marks as required (isRequired: true) is always refused when it is absent.

The constructor gets each value once, so a promoted property can be readonly. An exception that the constructor throws, for example for a value that it refuses, reaches the caller of toArrayObject() as it is.

class Point
{
    public function __construct(
        #[JsonProperty("x")] private float $_x,
        #[JsonProperty("y")] private float $_y
    ) {}

    public function getX(): float
    {
        return $this->_x;
    }

    public function getY(): float
    {
        return $this->_y;
    }
}

$point = Deserialize::toObject('{"x": 1.5, "y": 2.0}', Point::class);

3. Setter method injection

Annotate a public method when the JSON key does not correspond to any property name, or when you need to run logic on assignment. The method must accept exactly one parameter.

class Order
{
    private int $_idOrder;

    #[JsonProperty("id_order")]
    public function setOrderID(int $id): void
    {
        $this->_idOrder = $id;
    }

    public function getOrderID(): int
    {
        return $this->_idOrder;
    }
}

$order = Deserialize::toArrayObject(['id_order' => 99], Order::class);

Nested objects

When a property or parameter has a class type hint, deserialization recurses automatically into that class.

class Address
{
    #[JsonProperty("city")]
    private string $_city;

    public function getCity(): string
    {
        return $this->_city;
    }
}

class Customer
{
    #[JsonProperty("name")]
    private string $_name;

    #[JsonProperty("address")]
    private Address $_address;

    public function getName(): string
    {
        return $this->_name;
    }

    public function getAddress(): Address
    {
        return $this->_address;
    }
}

$json = '{"name": "Bob", "address": {"city": "Kyiv"}}';

$customer = Deserialize::toObject($json, Customer::class);
// $customer->getAddress()->getCity() === "Kyiv"

API reference

// Deserialize a JSON string into an instance of $className.
Deserialize::toObject(string $json, string $className): object

// Deserialize a pre-decoded PHP array into an instance of $className.
Deserialize::toArrayObject(array $data, string $className): object

Both methods throw core\json\JsonPropertyException when a method-level #[JsonProperty] has no name, and one of its two subclasses for the data:

Exception When getKey()
MissingValueException A required key is missing. The key.
InvalidValueException The type of a key cannot take its value, for example "five" for an int. getType() gives the type. The key.

A text of a whole number still goes into an int ("5" gives 5). For an int property or setter, an empty text or null gives 0 (or null for a nullable type), and a number with a fraction is refused. A constructor parameter gets the value as it is, with the conversion of PHP, as a method that a caller calls with the values: PHP refuses an empty text for an int there.

Schema generation

The description argument of #[JsonProperty] is exposed via DeserializeMapper::getProperties(), which returns an array of PropertyOptions objects. Use this to generate JSON schemas or API documentation from your PHP classes without extra annotation libraries.

use core\json\DeserializeMapper;
use core\json\JsonProperty;

class Product
{
    #[JsonProperty("sku", true, "Unique product identifier")]
    private string $_sku;

    #[JsonProperty("price", false, "Price in USD")]
    private float $_price;
}

$mapper = new DeserializeMapper(Product::class);

foreach ($mapper->getProperties() as $key => $injector) {
    $options = $injector->getOptions();
    // $options->getKey()          → "sku" / "price"
    // $options->getType()         → "string" / "float"
    // $options->isRequired()      → true / false
    // $options->isNullable()      → bool
    // $options->isObject()        → bool (true for class-typed properties)
    // $options->getDescription()  → "Unique product identifier" / "Price in USD"
    // $options->hasAttribute()    → true: the property has #[JsonProperty]
    // $options->hasDefaultValue() → bool; getDefaultValue() gives the default
}

getConstructorProperties() gives the options of each constructor parameter, keyed by its key, in the order of the parameters: a constructor parameter that is not promoted is only in this list. For these options, isRequired() says whether an absent key is refused (a nullable promoted parameter with no default and no isRequired: true is not required).

getProperties() lists each property of the class in the order of the declaration, then each setter with #[JsonProperty]. A property with no attribute is in the list too (it takes the key that is its name): hasAttribute() tells it apart. The default of a promoted property is the default of its constructor parameter.