PHPackages                             s-mcdonald/phpjson - 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. s-mcdonald/phpjson

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

s-mcdonald/phpjson
==================

PHPJson: An elegant and simple JSON object serialization library for PHP.

2.1.0(1y ago)1207—8.3%[4 PRs](https://github.com/s-mcdonald/PHPJson/pulls)MITPHPPHP ^8.2CI passing

Since Jan 1Pushed 4mo ago1 watchersCompare

[ Source](https://github.com/s-mcdonald/PHPJson)[ Packagist](https://packagist.org/packages/s-mcdonald/phpjson)[ GitHub Sponsors](https://github.com/s-mcdonald)[ RSS](/packages/s-mcdonald-phpjson/feed)WikiDiscussions master Synced 3w ago

READMEChangelogDependencies (6)Versions (24)Used By (0)

PHPJson
=======

[](#phpjson)

[![Source](https://camo.githubusercontent.com/b0fa7fe0a303018e8c3063b1480830471bb56c9f5ea456aca9d16eb312905baa/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f736f757263652d535f4d63446f6e616c642d626c75652e737667)](https://github.com/s-mcdonald/Json)[![License](https://camo.githubusercontent.com/51ff356b0630fd6605892f3e40e669aae495b0717a6a3044ce9f2d7d6109b98e/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f732d6d63646f6e616c642f7068706a736f6e)](https://camo.githubusercontent.com/51ff356b0630fd6605892f3e40e669aae495b0717a6a3044ce9f2d7d6109b98e/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f732d6d63646f6e616c642f7068706a736f6e)[![PHP Compatibility](https://camo.githubusercontent.com/391bfec36df1de3c53c1ecb8405b49148b1ac62e8e48a8f5992cdd14516c1e7f/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d253345253344382e322e302d626c7565)](https://camo.githubusercontent.com/391bfec36df1de3c53c1ecb8405b49148b1ac62e8e48a8f5992cdd14516c1e7f/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d253345253344382e322e302d626c7565)

[![Master Build Status](https://camo.githubusercontent.com/38ee81529c71397e53477ae89298a4715b5b734704dc8d9cd9950d97ad61df77/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f732d6d63646f6e616c642f7068706a736f6e2f7068702e796d6c3f6272616e63683d6d6173746572266c6162656c3d6d6173746572)](https://camo.githubusercontent.com/38ee81529c71397e53477ae89298a4715b5b734704dc8d9cd9950d97ad61df77/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f732d6d63646f6e616c642f7068706a736f6e2f7068702e796d6c3f6272616e63683d6d6173746572266c6162656c3d6d6173746572)[![Develop Build Status](https://camo.githubusercontent.com/0658493d69ab585dcef9496edd5cc5c1b58938da1f7ea798576e582e79dac590/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f732d6d63646f6e616c642f7068706a736f6e2f7068702e796d6c3f6272616e63683d646576656c6f70266c6162656c3d646576656c6f70)](https://camo.githubusercontent.com/0658493d69ab585dcef9496edd5cc5c1b58938da1f7ea798576e582e79dac590/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f732d6d63646f6e616c642f7068706a736f6e2f7068702e796d6c3f6272616e63683d646576656c6f70266c6162656c3d646576656c6f70)

[![Coverage Status](https://camo.githubusercontent.com/c94bedb0dd553078285e53253fdd3a73f0a47341874aac409d56ded9e7cdb779/68747470733a2f2f636f766572616c6c732e696f2f7265706f732f6769746875622f732d6d63646f6e616c642f5048504a736f6e2f62616467652e7376673f6272616e63683d646576656c6f70)](https://coveralls.io/github/s-mcdonald/PHPJson?branch=develop)

*A Fast and Lightweight PHP JSON Object Serialization Library.*

💖 Support This Project
----------------------

[](#-support-this-project)

`PHPJson` is supported by your donations! Click the **[Sponsor](https://github.com/sponsors/s-mcdonald)** link to display funding options.

---

`PHPJson` is a library that provides tools to work with JSON files and structures for PHP. Its primary feature is the ability to quickly and easily serialize PHP objects into JSON and deserialize (hydrate) JSON back to PHP objects.

Other features include

- Encode
- Decode
- Minify (uglify)
- Prettify
- Json Builder
- Serialization (including Enums)
- Serialization value casting
- Hydration
- Validation

Project Objectives
------------------

[](#project-objectives)

1. Simplify working with JSON structures.
2. Enable fast and minimal-configuration serialization using attributes.
3. Provide advanced serialization capabilities through traits and custom normalizers.
4. Reduce duplication in business logic by streamlining common tasks.

Contents
--------

[](#contents)

- [Usage](#Usage)
    - [Serialization](#serialization)
        - [Basic usage](#quick-usage)
        - [Override Json Properties](#override-json-properties)
        - [Nested Structures](#nested-structures)
        - [Serializing Enums](#serializing-enums)
        - [Casting values](#casting-values)
    - [Hydration/Deserialization](#deserialize-aka-object-hydration)
        - [Basic Hydration](#basic-hydration)
        - [Hydration with Setter Methods](#hydration-with-setter-methods)
    - [JsonBuilder](#jsonbuilder)
        - [Basic Builder](#jsonbuilder-basics)
        - [Objects and Arrays](#jsonbuilder-objects-and-arrays)
    - [Json Formatting](#json-formatting)
        - [Prettify](#prettify--Uglify)
    - [Json Validate](#json-validate)
- [Installation](#installation)
- [Dependencies](#dependencies)
- [License](#license)
- [Contribute](#contribute)

Usage
=====

[](#usage)

### Serialization

[](#serialization)

#### Quick usage

[](#quick-usage)

The fastest way to serialize a class into JSON is by using the `JsonProperty` attribute.

```
class User
{
    #[JsonProperty]
    public string $name;

    #[JsonProperty]
    public array $phoneNumbers;

    private int $creditCard;
}
```

```
{
    "name": "Foo",
    "phoneNumbers": [
        "044455444",
        "244755465"
    ]
}
```

```
$serializer = new JsonSerializer();
echo $serializer->serialize($user);
```

Or you can use the Json facade

```
echo Json::serialize($user); // outputs json
```

#### Override Json Properties

[](#override-json-properties)

You can customize property names in the JSON output by specifying your own names. This also applies when hydrating objects from JSON.

```
class User
{
    #[JsonProperty('userName')]
    public string $name;

    #[JsonProperty('numbers')]
    public array $phoneNumbers;

    private int $creditCard;
}
```

```
{
    "userName": "Foo",
    "numbers": [
        "044455444",
        "244755465"
    ]
}
```

#### Serialize from methods

[](#serialize-from-methods)

You can serialize values from getter methods, regardless of whether the method is public, protected, or private. `PHPJson` will automatically extract the value.

```
class User
{
    #[JsonProperty]
    public function authenticator(): string
    {
        return $this->authenticator;
    }

    #[JsonProperty('creditCardNumber')]
    public function getCreditCard(): int
    {
        return $this->creditCard;
    }
}
```

```
{
    "authenticator": "MasterCard",
    "creditCardNumber": "55044455444677"
}
```

#### Nested Structures

[](#nested-structures)

`PHPJson` allows you to work seamlessly with complex, nested objects. Nested classes and their properties are serialized into valid JSON structures, matching the relationships between objects.

```
class ParentClass
{
    #[JsonProperty('userName')]
    public string $name;

    #[JsonProperty('child')]
    public ChildClass $someChild;
}

class ChildClass
{
    public function __construct(
        #[JsonProperty('childProp')]
        private string $childProperty,
    ){
    }
}
```

```
$sut = new ParentClass();
$sut->name = 'fu';
$sut->someChild = new ChildClass("bar");
```

```
{
    "userName": "fu",
    "child": {
        "childProp": "bar"
    }
}
```

#### Serialization Using a trait

[](#serialization-using-a-trait)

The above method utilizes the JsonProperty to serialize any object. This is by far the easiest and fasted way to convert your objects into Json. However, this will have some limitations. To overcome this, we have included two Facets called `SerializesWithMapping` and `SerializesToJson`. With these Facets you can customize the Serialization and export vastly more complex objects.

#### Serializing Enums

[](#serializing-enums)

`PHPJson` supports the serialization of both pure and backed enums.

Pure Enum

```
enum Status
{
    case Enabled;
    case Disabled;
}

echo Json::serialize(Status::Enabled);
```

```
{
    "Status": "Enabled"
}
```

Backed Enum

```
enum Status: int
{
    case Enabled = 10;
    case Disabled = 20;
}

echo Json::serialize(Status::Enabled);
```

```
{
    "Status": 10
}
```

#### Casting Values

[](#casting-values)

When serializing a PHP object to JSON, you might need to cast specific property values into different types for the JSON output. You can achieve this by using the `JsonProperty` attribute to specify the desired type using a `JsonType`, such as `StringType` or `IntegerType`.

```
class
{
    #[JsonProperty(type: new StringType())]
    public float $myNumber = 123.456;

    #[JsonProperty(type: new IntegerType())]
    public float $myNumber2 = 123.456;
}
```

```
{
  "myNumber": "123.456",
  "myNumber2": 123
}
```

Available types are;

- StringType
- ArrayType,
- BooleanType,
- DoubleType,
- IntegerType,
- NullType,
- ObjectType

### Deserialize aka Object Hydration

[](#deserialize-aka-object-hydration)

#### Basic Hydration

[](#basic-hydration)

With `PHPJson`, basic object hydration is straightforward. If your class properties match the structure and property names in your JSON, no additional attributes or mappings are required. The library will automatically map the JSON data to your class or entity.

```
class MyUser
{
    public string $name;
    public int $age;
    public bool $isActive;
}
```

```
{
  "name": "Freddy",
  "age": 35,
  "isActive": true
}
```

Now deserialize the json string with the PHP class.

```
$myUser = Json::deserialize($json, MyUser::class);
```

```
YourNamespace\MyUser Object (
    'name' => 'Freddy'
    'age' => 35
    'isActive' => true
)

```

#### Hydration with Setter Methods

[](#hydration-with-setter-methods)

If your class relies on setters for processing or assigning values, `PHPJson` can hydrate using setter methods, provided these conditions are met:

- The setter accepts exactly one required argument.
- The `JsonProperty` attribute is used to specify the property for hydration.
- The argument type matches the data type in the JSON.
-

```
class MyUser
{
    #[JsonProperty('name')]
    public string $userName;

    public int $age;
    public bool $isActive;

    #[JsonProperty('name')]
    public function setUserName(string $value): void
    {
        $this->userName = 'foo: ' . $value;
    }
}
```

Notice how the JsonProperty is used twice here, for hydration setter methods will be the preferred hydration point, since, `setUserName` can not be used for serialization, the property `$userName` will be used for this.

### JsonBuilder

[](#jsonbuilder)

Fluently create Json objects using PHP.

#### JsonBuilder Basics

[](#jsonbuilder-basics)

```
$builder = Json::createJsonBuilder()
        ->addProperty('id', 11)
        ->addProperty('title', "Apple iOS 15")
        ->addProperty('rating', 4.26)
        ->addProperty('stock', 65);

echo $builder;
```

```
{
    "id": 11,
    "title": "Apple iOS 15",
    "rating": 4.26,
    "stock": 65
}
```

#### JsonBuilder Objects and Arrays

[](#jsonbuilder-objects-and-arrays)

```
$builder = Json::createJsonBuilder()
        ->addProperty('id', 11)
        ->addProperty('title', "Apple iOS 15")
        ->addProperty('rating', 4.26)
        ->addProperty('stock', 65);

echo $builder->addProperty(
            'thumbnail',
            Json::createJsonBuilder()
                ->addProperty("url", "https://i.dummyjson.com/data/products/11/thumbnail.jpg")
                ->addProperty("title", "thumbnail.jpg")
        )
        ->addProperty("images", [
            "https://i.dummyjson.com/data/products/11/1.jpg",
            "https://i.dummyjson.com/data/products/11/2.jpg"
        ])
;
```

```
{
    "id": 11,
    "title": "Apple iOS 15",
    "rating": 4.26,
    "stock": 65,
    "thumbnail": {
    "url": "https://i.dummyjson.com/data/products/11/thumbnail.jpg",
          "title": "thumbnail.jpg"
    },
    "images": [
          "https://i.dummyjson.com/data/products/11/1.jpg",
          "https://i.dummyjson.com/data/products/11/2.jpg"
     ]
}
```

### Json Formatting

[](#json-formatting)

#### Prettify &amp; Uglify

[](#prettify--uglify)

Prettify or Uglify(minify) your json values

```
Json::prettify('{"name":"bar","age":34}')
```

```
{
    "name": "bar",
    "age": 34
}
```

and then the reverse

```
Json::uglify('{
    "name": "bar",
    "age": 34
}')
```

```
{"name":"bar","age":34}
```

#### Json Validate

[](#json-validate)

PHP 8.3 onwards has the json\_validate function. This library duplicates this behaviour so it can bve used in PHP 8.2

```
Json::validate($json): bool

// or
json_validate($json): bool
```

Reference
=========

[](#reference)

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

[](#installation)

Install this package via composer, or simply fork/clone the repo.

```
composer require s-mcdonald/phpjson
```

Dependencies
------------

[](#dependencies)

- None

PHP Versions
------------

[](#php-versions)

- PHP 8.2, 8.3, 8.4

License
-------

[](#license)

Json is licensed under the terms of the [MIT License](http://opensource.org/licenses/MIT)(See LICENSE file for details).

Contribute
----------

[](#contribute)

🙌 Want to contribute?

Check out the issues section to get started.

[![Sponsor](https://camo.githubusercontent.com/2320df6dba257c358c5384493dcf34b4221238a33b344ef087451248b671bd51/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f53706f6e736f722d2545322539442541342d666636396234)](https://github.com/sponsors/s-mcdonald)

###  Health Score

40

—

FairBetter than 86% of packages

Maintenance63

Regular maintenance activity

Popularity16

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity61

Established project with proven stability

 Bus Factor1

Top contributor holds 98.3% 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 ~9 days

Recently: every ~36 days

Total

17

Last Release

389d ago

Major Versions

0.4.5 → 1.0.02025-01-11

1.0.0 → 2.0.02025-05-31

PHP version history (2 changes)0.0.3PHP &gt;=8.2

0.4.1PHP ^8.2

### Community

Maintainers

![](https://www.gravatar.com/avatar/1759b23f11dcfe1753788c7d3fe306af5bfcb11d1e199ccee0b8ad04b70bc00a?d=identicon)[S-McDonald](/maintainers/S-McDonald)

---

Top Contributors

[![s-mcdonald](https://avatars.githubusercontent.com/u/1879824?v=4)](https://github.com/s-mcdonald "s-mcdonald (283 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (5 commits)")

---

Tags

jsonphpserializationjsonserializerhydrationjson-phpphp-jsonphp-json-libraryjson-hydration

###  Code Quality

TestsPHPUnit

Static AnalysisRector

Code StylePHP\_CodeSniffer

### Embed Badge

![Health badge](/badges/s-mcdonald-phpjson/health.svg)

```
[![Health](https://phpackages.com/badges/s-mcdonald-phpjson/health.svg)](https://phpackages.com/packages/s-mcdonald-phpjson)
```

###  Alternatives

[zumba/json-serializer

Serialize PHP variables, including objects, in JSON format. Support to unserialize it too.

125770.3k15](/packages/zumba-json-serializer)[laktak/hjson

JSON for Humans. A configuration file format with relaxed syntax, fewer mistakes and more comments.

86241.3k14](/packages/laktak-hjson)[thunderer/serializard

Flexible serializer

2667.7k1](/packages/thunderer-serializard)[opensoft/simple-serializer

Simple Serializer

1914.2k1](/packages/opensoft-simple-serializer)

PHPackages © 2026

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