• Stars
    star
    124
  • Rank 287,328 (Top 6 %)
  • Language
    PHP
  • License
    MIT License
  • Created almost 11 years ago
  • Updated 12 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

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

Json Serializer for PHP

Software License Build Status Total Downloads Latest Stable Version

This is a library to serialize PHP variables in JSON format. It is similar of the serialize() function in PHP, but the output is a string JSON encoded. You can also unserialize the JSON generated by this tool and have you PHP content back.

Supported features:

  • Encode/Decode of scalar, null, array
  • Encode/Decode of objects
  • Encode/Decode of binary data
  • Support nested serialization
  • Support not declared properties on the original class definition (ie, properties in stdClass)
  • Support object recursion
  • Closures (via 3rd party library. See details below)

Unsupported serialization content:

  • Resource (ie, fopen() response)
  • NAN, INF constants

Limitations:

This project should not be confused with JsonSerializable interface added on PHP 5.4. This interface is used on json_encode to encode the objects. There is no unserialization with this interface, differently from this project.

Json Serializer requires PHP >= 7.0 and tested until PHP 8.2

Example

class MyCustomClass {
	public $isItAwesome = true;
	protected $nice = 'very!';
}

$instance = new MyCustomClass();

$serializer = new Zumba\JsonSerializer\JsonSerializer();
$json = $serializer->serialize($instance);
// $json will contain the content {"@type":"MyCustomClass","isItAwesome":true,"nice":"very!"}

$restoredInstance = $serializer->unserialize($json);
// $restoredInstance will be an instance of MyCustomClass

How to Install

If you are using composer, install the package zumba/json-serializer.

$ composer require zumba/json-serializer

Or add the zumba/json-serializer directly in your composer.json file.

If you are not using composer, you can just copy the files from src folder in your project.

Serializing Binary Strings

Binary strings introduce two special identifiers in the final json: @utf8encoded and @scalar. @utf8encoded is an array of keys from the original data which have their value (or the keys themselves) encoded from 8bit to UTF-8. This is how the serializer knows what to encode back from UTF-8 to 8bit when deserializing. Example:

$data = ['key' => '<binaryvalue>', 'anotherkey' => 'nonbinaryvalue'];
$serializer = new Zumba\JsonSerializer\JsonSerializer();
$json = $serializer->serialize($data);
// $json will contain the content {"key":"<utf8encodedbinaryvalue>","anotherkey":"nonbinaryvalue","@utf8encoded":{"key":1}}

@scalar is used only when the value to be encoded is not an array or an object but a binary string. Example:

$data = '<binaryvalue>';
$serializer = new Zumba\JsonSerializer\JsonSerializer();
$json = $serializer->serialize($data);
// $json will contain the content {"@scalar":"<utf8encodedbinaryvalue>","@utf8encoded":1}

Serializing Closure

For serializing PHP closures you can either use OpisClosure (preferred) or SuperClosure (the project is abandoned, so kept here for backward compatibility).

Closure serialization has some limitations. Please check the OpisClosure or SuperClosure project to check if it fits your needs.

To use the OpisClosure with JsonSerializer, just add it to the closure serializer list. Example:

$toBeSerialized = [
	'data' => [1, 2, 3],
	'worker' => function ($data) {
		$double = [];
		foreach ($data as $i => $number) {
			$double[$i] = $number * 2;
		}
		return $double;
	}
];

$jsonSerializer = new \Zumba\JsonSerializer\JsonSerializer();
$jsonSerializer->addClosureSerializer(new \Zumba\JsonSerializer\ClosureSerializer\OpisClosureSerializer());
$serialized = $jsonSerializer->serialize($toBeSerialized);

You can load multiple closure serializers in case you are migrating from SuperClosure to OpisClosure for example.

PS: JsonSerializer does not have a hard dependency of OpisClosure or SuperClosure. If you want to use both projects make sure you add both on your composer requirements and load them with addClosureSerializer() method.

Custom Serializers

Some classes may not be suited to be serialized and unserialized using the default reflection methods.

Custom serializers provide the ability to define serialize and unserialize methods for specific classes.

class MyType {
    public $field1;
    public $field2;
}

class MyTypeSerializer {
    public function serialize(MyType $obj) {
        return array('fields' => $obj->field1 . ' ' . $obj->field2);
    }

    public function unserialize($values) {
        list($field1, $field2) = explode(' ', $values['fields']);
        $obj = new MyType();
        $obj->field1 = $field1;
        $obj->field2 = $field2;
        return $obj;
    }
}

// map of "class name" => Custom serializer
$customObjectSerializers['MyType'] = new MyTypeSerializer();
$jsonSerializer = new Zumba\JsonSerializer\JsonSerializer(null, $customObjectSerializers);

$toBeSerialized = new MyType();
$toBeSerialized->field1 = 'x';
$toBeSerialized->field2 = 'y';
$json = $jsonSerializer->serialize($toBeSerialized);
// $json == {"@type":"Zumba\\\\JsonSerializer\\\\Test\\\\SupportClasses\\\\MyType","fields":"x y"}

$myType = $jsonSerializer->unserialize($json);
// $myType == $toBeSerialized

More Repositories

1

swivel

Strategy driven, segmented feature toggles
PHP
209
star
2

angular-waypoints

An AngularJS module for working with jQuery Waypoints
JavaScript
50
star
3

amplitude-php

Implementation of Amplitude's API in PHP
PHP
38
star
4

mongounit

PHPUnit extension that enables MongoDB data fixtures for test cases.
PHP
32
star
5

middleman.js

A small library that lets you inject some code between a third party library and the execution context.
JavaScript
27
star
6

elasticsearch-index-rotator

Safely rotate Elasticsearch indexes with no downtime to end users.
PHP
16
star
7

symbiosis

Event system for drop in support of plugin architecture.
PHP
13
star
8

drill-sergeant

Keep track and get notified when github pull requests become stale.
JavaScript
11
star
9

zumba.github.com

Zumba Public Engineering Site
HTML
9
star
10

zlogd

Socket server for external apps to ship logs in a non-blocking fashion.
JavaScript
9
star
11

csv-policy

Simple, policy-driven csv rules validation
PHP
8
star
12

swiveljs

Strategy driven, segmented feature toggles for Javascript
JavaScript
6
star
13

node-defender

Defend against waves of murderous server side code that wants nothing more than to kill and disconnect your node client.
JavaScript
6
star
14

zumba-coding-standards

Zumba's PHP Coding standards.
PHP
5
star
15

deadmanssnitch-php-sdk

Deadmanssnitch API SDK for PHP
PHP
4
star
16

elasticsearchunit

Elasticsearch extension for PHPUnit.
PHP
4
star
17

node-defender-game

Defend against waves of murderous server side code that wants nothing more than to kill and disconnect your node client.
JavaScript
3
star
18

swivel-cake

CakePHP plugin for Zumba\Swivel
PHP
2
star
19

vanilla-js-connect

Object oriented Vanilla Forums jsConnect implementation for PHP
PHP
2
star
20

cqrs

CQRS Framework
PHP
2
star
21

cloudfront-loggly-uploader

Upload AWS CloudFront logs to Loggly
Go
1
star