PHPackages                             denisyfrolov/json-serializer - 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. denisyfrolov/json-serializer

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

denisyfrolov/json-serializer
============================

Simple PHP serializer for any objects to JSON.

1.0.0(7y ago)08MITPHPPHP &gt;=7.0.19

Since Aug 11Pushed 7y ago1 watchersCompare

[ Source](https://github.com/denisyfrolov/json-serializer)[ Packagist](https://packagist.org/packages/denisyfrolov/json-serializer)[ RSS](/packages/denisyfrolov-json-serializer/feed)WikiDiscussions master Synced 2d ago

READMEChangelog (1)Dependencies (1)Versions (2)Used By (0)

Simple PHP serializer for any objects to JSON.
==============================================

[](#simple-php-serializer-for-any-objects-to-json)

[![Build Status](https://camo.githubusercontent.com/8fca1179cdffca25775cff9d8b8e8e16b452b94c115d3bae9b3dc5db6bafaa07/68747470733a2f2f7472617669732d63692e6f72672f64656e69737966726f6c6f762f6a736f6e2d73657269616c697a65722e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/denisyfrolov/json-serializer)[![Build Status](https://camo.githubusercontent.com/0d5e8799207243521908aa6c55565c395b289360ffa5be6682062b2c498b967b/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f64656e69737966726f6c6f762f6a736f6e2d73657269616c697a65722f6261646765732f6275696c642e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/denisyfrolov/json-serializer/build-status/master)[![Code Coverage](https://camo.githubusercontent.com/f3739e7790a2da31ef21a240a66220429b39022e6a15831c958a45241fc0d63d/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f64656e69737966726f6c6f762f6a736f6e2d73657269616c697a65722f6261646765732f636f7665726167652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/denisyfrolov/json-serializer/?branch=master)[![Scrutinizer Code Quality](https://camo.githubusercontent.com/80a488853a2a36c5f9d07078952b9c3c59902497a352f09b3d47425c59d511ac/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f64656e69737966726f6c6f762f6a736f6e2d73657269616c697a65722f6261646765732f7175616c6974792d73636f72652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/denisyfrolov/json-serializer/?branch=master)[![Code Intelligence Status](https://camo.githubusercontent.com/535cb5c092d56af3b8e0508da7f6e64421e924287578bc35b2e1c96117ad19b5/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f64656e69737966726f6c6f762f6a736f6e2d73657269616c697a65722f6261646765732f636f64652d696e74656c6c6967656e63652e7376673f623d6d6173746572)](https://scrutinizer-ci.com/code-intelligence)[![Latest Stable Version](https://camo.githubusercontent.com/bb40869117967b86545bad19aec20b0c8f4dbc79b2d4a9b3fb00b288a8c4cf28/68747470733a2f2f706f7365722e707567782e6f72672f64656e69737966726f6c6f762f6a736f6e2d73657269616c697a65722f762f737461626c65)](https://packagist.org/packages/denisyfrolov/json-serializer)[![Total Downloads](https://camo.githubusercontent.com/14134809c336e1037739e11f9d480dc8a0a0a4da4dd73377008e8fb598bd3e83/68747470733a2f2f706f7365722e707567782e6f72672f64656e69737966726f6c6f762f6a736f6e2d73657269616c697a65722f646f776e6c6f616473)](https://packagist.org/packages/denisyfrolov/json-serializer)[![License](https://camo.githubusercontent.com/01e4a177616d16761462269b66e58abb3b5b368c6073ecdc8fc5ffd7e5496212/68747470733a2f2f706f7365722e707567782e6f72672f64656e69737966726f6c6f762f6a736f6e2d73657269616c697a65722f6c6963656e7365)](https://packagist.org/packages/denisyfrolov/json-serializer)

- [Installation](#installation)
- [Introduction](#introduction)
- [Features](#features)
- [Serialization](#serialization)
- [Example](#example)
- [Quality](#quality)
- [Contribute](#contribute)
- [Author](#author)

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

[](#installation)

Use [Composer](https://getcomposer.org) to install the package:

```
$ composer require denisyfrolov/json-serializer
```

Introduction
------------

[](#introduction)

**What is serialization?**

In the context of data storage, serialization is the process of translating data structures or object state into a format that can be stored (for example, in a file or memory buffer, or transmitted across a network connection link) and reconstructed later in the same or another computer environment.

Features
--------

[](#features)

This is a very simple class which allows you to serialize any child objects to JSON.

- Recursively serializes all the properties you allow to serialize, including multidimensional arrays of objects of other classes.
- Uses annotations to customize the scheme for serialized objects and to mark which classes and properties should be serialized.
- Allows you to customize JSON's field names.
- Allows you to exclude any property of objects from serialization.
- Allows you to prevent serialization of any properties, classes of which should not be serialized.

Serialization
-------------

[](#serialization)

Make your class to be inherited from the serializator class `JsonSerializableObject`:

```
use JsonSerializer\JsonSerializableObject;

class Order extends JsonSerializableObject
{

}
```

Mark your class as serializable using the flag `@JsonSerializable` in an annotations area of the class:

```
use JsonSerializer\JsonSerializableObject;

/**
 * @JsonSerializable
 */
class Order extends JsonSerializableObject
{

}
```

If your class uses different classes as types for properties you want to serialize, mark all of these classes as serializable too. Otherwise the exception will be thrown: `Class ClassName is not marked as serializable`.

Make getters for all the properties you want to serialize. Also make the properties publicly accessible:

```
use JsonSerializer\JsonSerializableObject;

/**
 * @JsonSerializable
 */
class Order extends JsonSerializableObject
{
    /**
     * @var integer
     */
    private $orderId = 0;

    /**
     * Get OrderId
     *
     * @return int
     */
    public function getOrderId(): int
    {
        return $this->orderId;
    }

    /**
     * Set OrderId
     *
     * @param integer $orderId
     *
     * @return Order
     */
    public function setOrderId(int $orderId): Order
    {
        $this->orderId = $orderId;

        return $this;
    }
}
```

By default the serializer uses property names as field names in JSON's schema. If you want to customize the names in the schema, use `@JsonPropertyName property_name` keyword in an annotations area of the property:

```
use JsonSerializer\JsonSerializableObject;

/**
 * @JsonSerializable
 */
class Order extends JsonSerializableObject
{
    /**
     * @JsonPropertyName order_id
     *
     * @var integer
     */
    private $orderId = 0;

    /**
     * Get OrderId
     *
     * @return int
     */
    public function getOrderId(): int
    {
        return $this->orderId;
    }

    /**
     * Set OrderId
     *
     * @param integer $orderId
     *
     * @return Order
     */
    public function setOrderId(int $orderId): Order
    {
        $this->orderId = $orderId;

        return $this;
    }
}
```

To prevent any properties from serialization, mark the properties as **Non Serializable** using keyword `@JsonPropertyNonSerializable` in an annotations area of the property:

```
use JsonSerializer\JsonSerializableObject;

/**
 * @JsonSerializable
 */
class Order extends JsonSerializableObject
{
    /**
     * @JsonPropertyName order_id
     *
     * @var integer
     */
    private $orderId = 0;

    /**
     * @JsonPropertyNonSerializable
     *
     * @var float
     */
    private $amount = 0;

    /**
     * Get OrderId
     *
     * @return int
     */
    public function getOrderId(): int
    {
        return $this->orderId;
    }

    /**
     * Set OrderId
     *
     * @param integer $orderId
     *
     * @return Order
     */
    public function setOrderId(int $orderId): Order
    {
        $this->orderId = $orderId;

        return $this;
    }

    /**
     * Get Amount
     *
     * @return float
     */
    public function getAmount(): float
    {
        return $this->amount;
    }

    /**
     * Set Amount
     *
     * @param float $amount
     *
     * @return Order
     */
    public function setAmount(float $amount): Order
    {
        $this->amount = $amount;

        return $this;
    }
}
```

Call `jsonSerialize()` method to serialize your object to JSON format.

```
require_once '../vendor/autoload.php';

$order = new Order();
$order->setOrderId(12345);
$order->setAmount(100);

print $order->jsonSerialize();
```

**Output**

```
{
    "order_id": 12345,
    "amount": 100
}
```

### Example

[](#example)

You can find this example with all the classes in `example` folder of the project.

**Code**

```
use JsonSerializer\JsonSerializableObject;

/**
 * Order
 *
 * @JsonSerializable
 *
 */
class Order extends JsonSerializableObject
{
    /**
     * @JsonPropertyName order_id
     *
     * @var integer
     */
    private $orderId = 0;

    /**
     * @JsonPropertyName customer
     *
     * @var Customer
     */
    private $customer;

    /**
     * @JsonPropertyName products
     *
     * @var array
     */
    private $products = array();

    /**
     * Get OrderId
     *
     * @return int
     */
    public function getOrderId(): int
    {
        return $this->orderId;
    }

    /**
     * Set OrderId
     *
     * @param integer $orderId
     *
     * @return Order
     */
    public function setOrderId(int $orderId): Order
    {
        $this->orderId = $orderId;

        return $this;
    }

    /**
     * Get customer
     *
     * @return Customer
     */
    public function getCustomer(): Customer
    {
        return $this->customer !== null ? $this->customer : new Customer();
    }

    /**
     * Set customer
     *
     * @param Customer $customer
     *
     * @return Order
     */
    public function setCustomer(Customer $customer): Order
    {
        $this->customer = $customer;

        return $this;
    }

    /**
     * Get Products
     *
     * @return array
     */
    public function getProducts(): array
    {
        return ($this->products !== null and is_array($this->products) and count($this->products) > 0) ? $this->products : array(new Product());
    }

    /**
     * Add Product
     *
     * @param Product $product
     *
     * @return Order
     */
    public function addProduct(Product $product): Order
    {
        $this->products[] = $product;

        return $this;
    }

}
```

```
require_once '../vendor/autoload.php';
require_once 'Order.php';
require_once 'Product.php';
require_once 'Customer.php';

$customer = new Customer();
$customer->setName('Test Customer Name');
$customer->setEmail('example@email.com');

$product = new Product();
$product->setName('Test Product 1 Name');
$product->setQuantity(2);
$product->setPrice(10.52);

$product2 = new Product();
$product2->setName('Test Product 2 Name');
$product2->setQuantity(4);
$product2->setPrice(11.53);

$order = new Order();
$order->setOrderId(12345);
$order->setCustomer($customer);
$order->addProduct($product);
$order->addProduct($product2);

print $order->jsonSerialize();
```

**Output**

```
{
    "order_id": 12345,
    "customer": {
        "name": "Test Customer Name",
        "email": "example@email.com"
    },
    "products": [
        {
            "name": "Test Product 1 Name",
            "quantity": 2,
            "price": 10.52,
            "amount": 21.04
        },
        {
            "name": "Test Product 2 Name",
            "quantity": 4,
            "price": 11.53,
            "amount": 46.12
        }
    ]
}
```

Quality
-------

[](#quality)

To run the PHPUnit tests at the command line, go to the project's root directory and issue `phpunit`.

This library attempts to comply with [PSR-4](http://www.php-fig.org/psr/psr-4/).

If you notice compliance oversights, please send a patch via pull request.

Contribute
----------

[](#contribute)

Contributions to the package are always welcome!

- Report any bugs or issues you find on the [issue tracker](https://github.com/denisyfrolov/json-serializer/issues/new).
- You can grab the source code at the package's [Git repository](https://github.com/denisyfrolov/json-serializer).

Author
------

[](#author)

- [Denis Y Frolov](https://twitter.com/denisyfrolov)

License
-------

[](#license)

The code base is licensed under the MIT license.

###  Health Score

24

—

LowBetter than 32% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity4

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity57

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

2834d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/8500e69e1e20162518efc32aebfb8cac1dc2cdb9fb34469c1d23947b495c0bc2?d=identicon)[denisyfrolov](/maintainers/denisyfrolov)

---

Top Contributors

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

---

Tags

jsonserializeserializer

### Embed Badge

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

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

###  Alternatives

[zumba/json-serializer

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

129743.7k13](/packages/zumba-json-serializer)[laktak/hjson

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

86233.7k12](/packages/laktak-hjson)[thunderer/serializard

Flexible serializer

2767.3k1](/packages/thunderer-serializard)[pmjones/throwable-properties

Copies properties of a Throwable to a serializable object.

1554.7k2](/packages/pmjones-throwable-properties)

PHPackages © 2026

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