PHPackages                             sergey144010/json - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. sergey144010/json

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

sergey144010/json
=================

Json to object

v1.0.0(1y ago)0946↓33.3%PHPPHP ^8.1

Since May 5Pushed 1y ago1 watchersCompare

[ Source](https://github.com/sergey144010/json)[ Packagist](https://packagist.org/packages/sergey144010/json)[ RSS](/packages/sergey144010-json/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (1)Dependencies (4)Versions (3)Used By (0)

json
====

[](#json)

Json to object

Get from json named object with properties.

For more details see

Examples
--------

[](#examples)

Initialization

```
use Sergey144010\Json\JsonWrapper;

$this->json = new JsonWrapper(
    new Data(new CamelCustom())
);

```

-

```
### Input json
{"property-one": "one", "property_two": "two"}

### Named Dto
class SomeDto
{
    public function __construct(
        readonly public string $propertyOne,
        readonly public string $propertyTwo,
    ) {
    }
}

### Output

$dto = $this->json->toObject($string, SomeDto::class);

self::assertEquals('one', $dto->propertyOne);
self::assertEquals('two', $dto->propertyTwo);

```

-

```
### Input json

$data = '
{
    "one": {
        "propertyOne": "one1",
        "propertyTwo": "two1"
    },
    "two": {
        "propertyOne": "one2",
        "propertyTwo": "two2"
    }
}
';

### Dto
class RootDto
{
    public function __construct(
        readonly public SomeDto $one,
        readonly public SomeDto $two,
    ) {
    }
}

### Output

$dto = $this->json->toObject($data, RootDto::class);
echo $dto->one->propertyOne; // one1
echo $dto->one->propertyTwo; // two1
echo $dto->two->propertyOne; // one2
echo $dto->two->propertyTwo; // two2

```

-

```
# Input data

$data = json_encode([
    'one' => [
        'propertyOne' => 'one',
        'propertyTwo' => 'two',
    ],
    'collection' => [
        [
            'propertyOne' => 'one1',
            'propertyTwo' => 'two1',
        ],
        [
            'propertyOne' => 'one2',
            'propertyTwo' => 'two2',
        ],
    ],
]);

# Dto
use Sergey144010\Data\Attribute\Collection;

class CollectionDto
{
    public function __construct(
        readonly public SomeDto $one,
        #[Collection(SomeDto::class)] readonly public array $collection,
    ) {
    }
}

# Output

$dto = $json->toObject($data, CollectionDto::class);
echo $dto->one->propertyOne; // one
echo $dto->one->propertyTwo; // two
echo $dto->collection[0]->propertyOne; // one1
echo $dto->collection[0]->propertyTwo; // two1
echo $dto->collection[1]->propertyOne; // one2
echo $dto->collection[1]->propertyTwo; // two2

```

-

```
# Input data

$data = json_encode([
    [
        'propertyOne' => 11,
        'propertyTwo' => 12,
    ],
    [
        'propertyOne' => 21,
        'propertyTwo' => 22,
    ],
]);

# Dto
use Sergey144010\Data\Attribute\CollectionRoot;

class CollectionDto
{
    public function __construct(
        readonly public SomeDto $one,
        #[CollectionRoot(SomeDto::class)] readonly public array $collection,
    ) {
    }
}

# Output

$dto = $json->toObject($data, CollectionDto::class);
echo $dto->collection[0]->propertyOne; // 11
echo $dto->collection[0]->propertyTwo; // 12
echo $dto->collection[1]->propertyOne; // 21
echo $dto->collection[1]->propertyTwo; // 22

```

-

```
# Input data

$data = json_encode([
    'propertyOne' => [359418786]
]);

# Dto

class ConstructorPropertyArrayModel
{
    public function __construct(
        readonly public array $propertyOne
    ) {
    }
}

# Output

$dto = $json->toObject($data, ConstructorPropertyArrayModel::class);
echo $dto->propertyOne[0]; // 359418786

```

With Interfaces
---------------

[](#with-interfaces)

-

```
        $data = json_encode([
            'one' => [
                'property-one' => 'one',
            ],
            'two' => [
                'property-two' => 'two',
            ],
        ]);

        $model = $json->toObject(
            jsonString: $data,
            class: ModelPropertyTwo::class,
            injectionMap: [
                ModelInterface::class => ModelClass::class,
                ModelInterfaceTwo::class => ModelClassTwo::class,
            ]
        );

        self::assertEquals('one', $model->one->propertyOne);
        self::assertEquals('two', $model->two->propertyTwo);

# Where
class ModelPropertyTwo
{
    public readonly ModelInterface $one;
    public readonly ModelInterfaceTwo $two;
}

class ModelClass implements ModelInterface
{
    public readonly string $propertyOne;
}

class ModelClassTwo implements ModelInterfaceTwo
{
    public readonly string $propertyTwo;
}

```

-

```
        $data = json_encode([
            'one' => [
                'property-one' => 'one',
            ],
            'two' => [
                'property-two' => 'two',
            ],
        ]);

        $model = $json->toObject(
            jsonString: $data,
            class: EntryModelTwo::class,
            injectionMap: [
                EntryModelTwo::class => [
                    'one' => ModelOne::class,
                    'two' => ModelTwo::class,
                ]
            ]
        );

        self::assertEquals('one', $model->one->propertyOne);
        self::assertEquals('two', $model->two->propertyTwo);

# Where
class EntryModelTwo
{
    public function __construct(
        readonly public ModelInterfaceBase $one,
        readonly public ModelInterfaceBase $two,
    ) {
    }
}

class ModelOne implements ModelInterfaceBase
{
    public function __construct(
        readonly public string $propertyOne,
    ) {
    }
}

class ModelTwo implements ModelInterfaceBase
{
    public function __construct(
        readonly public string $propertyTwo,
    ) {
    }
}

```

-

```
        $string = json_encode(
            [
                'one' => [
                    'property-two' => 'two',
                ],
            ]
        );

        $model = $this->json->toObject(
            jsonString: $string,
            class: EntryModelOne::class,
            injectionMap: function (array $request) {
                if (isset($request['one']['property-one'])) {
                    return [ModelInterfaceBase::class => ModelOne::class];
                }
                if (isset($request['one']['property-two'])) {
                    return [ModelInterfaceBase::class => ModelTwo::class];
                }

                return [];
            }
        );

        self::assertEquals('two', $model->one->propertyTwo);

```

About Strategy
==============

[](#about-strategy)

Есть несколько стратегий заполнения свойств объекта:

- Через конструктор. Только свойства описанные в конструкторе попадут в объект. Strategy\\Constructor.
- Через публичные свойства объекта. Только свойства описанные как публичные свойства объекта попадут в объект. Strategy\\Properties.
- Сначала проверка есть ли что-то в конструкторе, а потом проверка публичных свойств. Strategy\\StepByStep - по умолчанию.
- Добавление всех входящих данных как публичные свойства объекта. Strategy\\AddProperties.

There are several strategies for filling object properties:

- Via a constructor. Only properties described in the constructor will be included in the object. Strategy\\Constructor.
- Via public properties of the object. Only properties described as public properties of the object will be included in the object. Strategy\\Properties.
- First, check if there is something in the constructor, and then check the public properties. Strategy\\StepByStep - by default.
- Add all incoming data as public properties of the object. Strategy\\AddProperties.

Examples strategy
=================

[](#examples-strategy)

- Constructor

```
class SomeDto
{
    public function __construct(
        readonly public string $propertyOne,
    ) {
    }
}

$json->toObject(
    jsonString:$data,
    class: SomeDto::class,
    strategy: new Strategy\Constructor()
    );

```

- Public properties

```
class SomeDto
{
    public string $propertyOne;
}

$json->toObject(
    jsonString:$data,
    class: SomeDto::class,
    strategy: new Strategy\Properties()
    );

```

- Combine Constructor and public properties

```
$json->toObject(
    jsonString:$data,
    class: SomeDto::class,
    strategy: new Strategy\StepByStep()
);

```

- Simple add properties

```
class SomeDto
{
}

$data = [
    'one' => 1,
    'two' => 2,
]

$json->toObject(
    jsonString:$data,
    class: SomeDto::class,
    strategy: new Strategy\AddProperties()
);

echo $data->one; // 1
echo $data->two; // 2

```

For more details see

Code style, Static analyze, Tests
=================================

[](#code-style-static-analyze-tests)

Need checkout tests branch

Build
-----

[](#build)

```
$ docker build -t test-json-image-php8.1 -f ./docker/Dockerfile-php8.1 ./docker

```

Install
-------

[](#install)

```
$ docker run -it --rm --name json-tests -v "$PWD":/usr/src/app -w /usr/src/app test-json-image-php8.1 composer install

```

Code style
----------

[](#code-style)

```
$ docker run -it --rm --name json-tests -v "$PWD":/usr/src/app -w /usr/src/app test-json-image-php8.1 php ./vendor/bin/phpcs --standard=PSR12 -p ./src ./tests
$ docker run -it --rm --name json-tests -v "$PWD":/usr/src/app -w /usr/src/app test-json-image-php8.1 php ./vendor/bin/phpcbf --standard=PSR12 -p ./src ./tests

```

Static analyze
--------------

[](#static-analyze)

```
$ docker run -it --rm --name json-tests -v "$PWD":/usr/src/app -w /usr/src/app test-json-image-php8.1 php ./vendor/bin/phpstan analyze --level=5 ./src

```

Tests
-----

[](#tests)

```
$ docker run -it --rm --name json-tests -v "$PWD":/usr/src/app -w /usr/src/app test-json-image-php8.1 php ./vendor/bin/phpunit --bootstrap ./vendor/autoload.php ./tests

```

###  Health Score

33

—

LowBetter than 75% of packages

Maintenance49

Moderate activity, may be stable

Popularity18

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity47

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

378d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/594ac8d87dcafa11ab96473cfc44c3ebb474792544c060ce3355f9a67f527195?d=identicon)[sergey144010](/maintainers/sergey144010)

---

Top Contributors

[![sergey144010](https://avatars.githubusercontent.com/u/11247861?v=4)](https://github.com/sergey144010 "sergey144010 (1 commits)")

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP\_CodeSniffer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/sergey144010-json/health.svg)

```
[![Health](https://phpackages.com/badges/sergey144010-json/health.svg)](https://phpackages.com/packages/sergey144010-json)
```

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
