Coder Social home page Coder Social logo

effiana / json-serializer Goto Github PK

View Code? Open in Web Editor NEW

This project forked from zumba/json-serializer

0.0 1.0 0.0 92 KB

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

Home Page: http://tech.zumba.com/2014/01/06/json-serializer/

License: MIT License

PHP 100.00%

json-serializer's Introduction

Json Serializer for PHP

Software License Build Status Code Coverage Scrutinizer

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 >= 5.4 and tested until PHP 7.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 Closures

For serializing PHP closures you have to pass an object implementing SuperClosure\SerializerInterface. This interface is provided by the project SuperClosure. This project also provides a closure serializer that implements this interface.

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

To use the SuperClosure with JsonSerializer, just pass the SuperClosure object as the first parameter on JsonSerializer constructor. Example:

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

$superClosure = new SuperClosure\Serializer();
$jsonSerializer = new Zumba\JsonSerializer\JsonSerializer($superClosure);
$serialized = $jsonSerializer->serialize($toBeSerialized);

PS: JsonSerializer does not have a hard dependency of SuperClosure. If you want to use both projects make sure you add both on your composer requirements.

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

json-serializer's People

Contributors

aramonc avatar cjsaylor avatar ghola avatar jrbasso avatar maxgfeller avatar sourceguardian avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.