PHPackages                             karriere/json-decoder - 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. [Parsing &amp; Serialization](/categories/parsing)
4. /
5. karriere/json-decoder

ActiveLibrary[Parsing &amp; Serialization](/categories/parsing)

karriere/json-decoder
=====================

JsonDecoder implementation that allows you to convert your JSON data into PHP class objects

v5.1.0(3mo ago)140425.9k↓18.2%23[1 issues](https://github.com/karriereat/json-decoder/issues)12Apache-2.0PHPPHP ^8.2CI passing

Since Apr 24Pushed 3mo ago12 watchersCompare

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

READMEChangelog (10)Dependencies (4)Versions (24)Used By (12)

[![](https://raw.githubusercontent.com/karriereat/.github/main/profile/logo.svg)](https://www.karriere.at/) [![](https://github.com/karriereat/json-decoder/workflows/CI/badge.svg)](https://github.com/karriereat/json-decoder/workflows/CI/badge.svg)[![Packagist Downloads](https://camo.githubusercontent.com/ab99c8d868102845a17626fe7df6a09aad4bb9391c50c3e5d1ac3594cd0c6da4/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6b617272696572652f6a736f6e2d6465636f6465722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/karriere/json-decoder)

JsonDecoder for PHP
===================

[](#jsondecoder-for-php)

This package contains a JsonDecoder implementation that allows you to convert your JSON data into php class objects other than `stdclass`.

Installation
------------

[](#installation)

You can install the package via composer

```
composer require karriere/json-decoder

```

Usage
-----

[](#usage)

By default the Decoder will iterate over all JSON fields defined and will try to set this values on the given class type instance. This change in behavior allows the use of `json-decoder` on classes that use the **magic** `__get` and `__set` functions like Laravel's Eloquent models.

If a property equally named like the JSON field is found or a explicit `Binding` is defined for the JSON field it will be decoded into the defined place. Otherwise the property will just be created and assigned (you need the `#[AllowDynamicProperties]` attribute if you are on PHP 8.2.).

The `JsonDecoder` class can receive one parameter called `shouldAutoCase`. If set to true it will try to find the camel-case version from either snake-case or kebap-case automatically if no other binding was registered for the field and it will use an `AliasBinding` if one of the variants can be found.

### A simple example

[](#a-simple-example)

Assume you have a class `Person` that looks like this:

```
#[AllowDynamicProperties]
class Person
{
    public int $id;
    public string $name;
    public ?string $lastname = '';
}
```

The following code will transform the given JSON data into an instance of `Person`.

```
$jsonDecoder = new JsonDecoder();
$jsonData = '{"id": 1, "name": "John Doe", "lastname": null, "dynamicProperty": "foo"}';

$person = $jsonDecoder->decode($jsonData, Person::class);
```

Please be aware that since PHP 8.2. dynamic properties are deprecated. So if you still wish to have the ability to make use of those dynamic properties you have to add the PHP attribute `AllowDynamicProperties` to your class. If you are using PHP 8.2. (and greater) and don't use the `AllowDynamicProperties` attribute all dynamic properties will be ignored.

### More complex use case

[](#more-complex-use-case)

Let's extend the previous example with a property called address. This address field should contain an instance of `Address`. As of version 4 you can use the introduced method `scanAndRegister` to automatically generate the transformer based on class annotations. Since version 5 you can also make use of the property type instead of a class annotation.

```
class Person
{
    public int $id;
    public string $name;

    /**
     * @var Address
     */
    public $address;

    public ?Address $typedAddress = null;
}
```

For this class definition we can decode JSON data as follows:

```
$jsonDecoder = new JsonDecoder();
$jsonDecoder->scanAndRegister(Person::class);

$jsonData = '{"id": 1, "name": "John Doe", "address": {"street": "Samplestreet", "city": "Samplecity"}, , "typedAddress": {"street": "Samplestreet", "city": "Samplecity"}}';

$person = $jsonDecoder->decode($jsonData, Person::class);
```

### Defining a Transformer

[](#defining-a-transformer)

If you don't use annotations or need a more flexible `Transformer` you can also create a custom transformer. Let's look at the previous example without annotation.

```
class Person
{
    public int $id;
    public string $name;
    public mixed $address;
}
```

To be able to transform the address data into an `Address` class object you need to define a transformer for `Person`:

The transformer interface defines two methods:

- register: here you register your field, array, alias and callback bindings
- transforms: gives you the full qualified class name e.g.: Your\\Namespace\\Class

```
class PersonTransformer implements Transformer
{
    public function register(ClassBindings $classBindings)
    {
        $classBindings->register(new FieldBinding('address', 'address', Address::class));
    }

    public function transforms()
    {
        return Person::class;
    }
}
```

After registering the transformer the `JsonDecoder` will use the defined transformer:

```
$jsonDecoder = new JsonDecoder();
$jsonDecoder->register(new PersonTransformer());

$jsonData = '{"id": 1, "name": "John Doe"}';

$person = $jsonDecoder->decode($jsonData, Person::class);
```

### Handling private and protected properties

[](#handling-private-and-protected-properties)

As of version 4 the `JsonDecoder` class will handle `private` and `protected` properties out of the box.

### Transforming an array of elements

[](#transforming-an-array-of-elements)

If your JSON contains an array of elements at the root level you can use the `decodeMultiple` method to transform the JSON data into an array of class type objects.

```
$jsonDecoder = new JsonDecoder();

$jsonData = '[{"id": 1, "name": "John Doe"}, {"id": 2, "name": "Jane Doe"}]';

$personArray = $jsonDecoder->decodeMultiple($jsonData, Person::class);
```

Documentation
-------------

[](#documentation)

### Transformer Bindings

[](#transformer-bindings)

The following `Binding` implementations are available

- [FieldBinding](#fieldbinding)
- [ArrayBinding](#arraybinding)
- [AliasBinding](#aliasbinding)
- [DateTimeBinding](#datetimebinding)
- [CallbackBinding](#callbackbinding)

#### FieldBinding

[](#fieldbinding)

Defines a JSON field to property binding for the given type.

**Signature:**

```
new FieldBinding(string $property, ?string $jsonField = null, ?string $type = null, bool $isRequired = false);
```

This defines a field mapping for the property `$property` to a class instance of type `$type` with data in `$jsonField`.

#### ArrayBinding

[](#arraybinding)

Defines an array field binding for the given type.

**Signature:**

```
new ArrayBinding(string $property, ?string $jsonField = null, ?string $type = null, bool $isRequired = false);
```

This defines a field mapping for the property `$property` to an array of class instance of type `$type` with data in `$jsonField`.

#### AliasBinding

[](#aliasbinding)

Defines a JSON field to property binding.

**Signature:**

```
new AliasBinding(string $property, ?string $jsonField = null, bool $isRequired = false);
```

#### DateTimeBinding

[](#datetimebinding)

Defines a JSON field to property binding and converts the given string to a `DateTime` instance.

**Signature:**

```
new DateTimeBinding(string $property, ?string $jsonField = null, bool $isRequired = false, $dateTimeFormat = DateTime::ATOM);
```

#### CallbackBinding

[](#callbackbinding)

Defines a property binding that gets the callback result set as its value.

**Signature:**

```
new CallbackBinding(string $property, private Closure $callback);
```

License
-------

[](#license)

Apache License 2.0 Please see [LICENSE](LICENSE) for more information.

###  Health Score

66

—

FairBetter than 99% of packages

Maintenance82

Actively maintained with recent releases

Popularity52

Moderate usage in the ecosystem

Community32

Small or concentrated contributor base

Maturity85

Battle-tested with a long release history

 Bus Factor1

Top contributor holds 85.7% 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

Every ~153 days

Recently: every ~372 days

Total

22

Last Release

90d ago

Major Versions

v1.2.0 → v2.0.02017-12-19

v2.2.1 → v3.0.02020-03-25

v3.1.0 → v4.0.02020-10-06

v4.2.0 → v5.0.02023-03-01

PHP version history (8 changes)v1.0.0PHP &gt;=5.6

v2.0.0PHP &gt;=7.0

v3.0.0PHP &gt;=7.2

v4.0.0PHP &gt;=7.3

v4.1.0PHP ^7.3 | ^8.0

v5.0.0PHP 8.0.\* | 8.1.\* | 8.2.\*

v5.0.1PHP 8.0.\* | 8.1.\* | 8.2.\* | 8.3.\* | 8.4.\*

v5.1.0PHP ^8.2

### Community

Maintainers

![](https://www.gravatar.com/avatar/b155d5296b644a0e937677b500bee7983ce4a91294b616d7a690e57f5b14a3aa?d=identicon)[fetzi](/maintainers/fetzi)

![](https://www.gravatar.com/avatar/59ac000ca995a016e613c45c25d9b9c319853c5a783299aa5cc059f2c4477aab?d=identicon)[karriere-at-dev](/maintainers/karriere-at-dev)

---

Top Contributors

[![fetzi](https://avatars.githubusercontent.com/u/3509426?v=4)](https://github.com/fetzi "fetzi (78 commits)")[![otsch](https://avatars.githubusercontent.com/u/4062813?v=4)](https://github.com/otsch "otsch (5 commits)")[![lentex](https://avatars.githubusercontent.com/u/9319316?v=4)](https://github.com/lentex "lentex (3 commits)")[![mrowdy](https://avatars.githubusercontent.com/u/4717157?v=4)](https://github.com/mrowdy "mrowdy (3 commits)")[![jaylinski](https://avatars.githubusercontent.com/u/1668766?v=4)](https://github.com/jaylinski "jaylinski (1 commits)")[![lfbn](https://avatars.githubusercontent.com/u/6152567?v=4)](https://github.com/lfbn "lfbn (1 commits)")

---

Tags

jsonjson-datajson-decodingjsondecoderphpphp-jsonjsondecoder

###  Code Quality

TestsPest

Static AnalysisPHPStan

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

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

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

###  Alternatives

[justinrainbow/json-schema

A library to validate a json schema.

3.6k316.9M612](/packages/justinrainbow-json-schema)[mtdowling/jmespath.php

Declaratively specify how to extract elements from a JSON document

2.0k472.8M135](/packages/mtdowling-jmespathphp)[jms/serializer

Library for (de-)serializing data of any complexity; supports XML, and JSON.

2.3k135.8M851](/packages/jms-serializer)[jms/serializer-bundle

Allows you to easily serialize, and deserialize data of any complexity

1.8k89.3M627](/packages/jms-serializer-bundle)[colinodell/json5

UTF-8 compatible JSON5 parser for PHP

30422.2M45](/packages/colinodell-json5)[clue/ndjson-react

Streaming newline-delimited JSON (NDJSON) parser and encoder for ReactPHP.

15467.7M16](/packages/clue-ndjson-react)

PHPackages © 2026

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