Php serialize object to json

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Simple PHP serializer for any objects to JSON.

License

denisyfrolov/json-serializer

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Simple PHP serializer for any objects to JSON.

Build Status Code Coverage Scrutinizer Code Quality

Use Composer to install the package:

$ composer require denisyfrolov/json-serializer

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.

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.

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();
< "order_id": 12345, "amount": 100 >

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

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();
< "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 > ] >

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.

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

Contributions to the package are always welcome!

  • Report any bugs or issues you find on the issue tracker.
  • You can grab the source code at the package’s Git repository.

The code base is licensed under the MIT license.

About

Simple PHP serializer for any objects to JSON.

Источник

PHP JSON

Summary: in this tutorial, you will learn how to convert data in PHP to JSON data and vice versa using the PHP JSON extension.

JSON stands for JavaScript Object Notation. JSON is designed as a lightweight data-interchange format.

JSON is built on two structures:

  • A collection of name/value pairs called JSON objects. JSON objects are equivalent to associative arrays in PHP.
  • An ordered list of values called arrays. They’re equivalent to indexed arrays in PHP.

The JSON format is human-readable and easy for computers to parse. Even though JSON syntax derives from JavaScript, it’s designed to be language-independent.

PHP JSON extension

PHP natively supports JSON via the JSON extension. The JSON extension provides you with some handy functions that convert data from PHP to JSON format and vice versa.

Since the JSON extension comes with PHP installation by default, you don’t need to do any extra configuration to make it works.

Converting PHP variables to JSON using json_encode() function

To get a JSON representation of a variable, you use the json_encode() function:

json_encode ( mixed $value , int $flags = 0 , int $depth = 512 ) : string|falseCode language: PHP (php)

The following example uses the json_encode() function to convert an indexed array in PHP to JSON format:

 $names = ['Alice', 'Bob', 'John']; $json_data = json_encode($names); // return JSON to the browsers header('Content-type:application/json'); echo $json_data;Code language: PHP (php)
  • First, define an array of strings that consists of three elements.
  • Second, convert the array to JSON using the json_encode() function.
  • Third, return the JSON data to the browsers by setting the content type of the document to appplication/json using the header() function.
[ "Alice", "Bob", "John" ]Code language: JSON / JSON with Comments (json)

The following example uses the json_encode() function to convert an associative array in PHP to an object in JSON:

 $person = [ 'name' => 'Alice', 'age' => 20 ]; header('Content-type:application/json'); echo json_encode($person);Code language: PHP (php)
< name: "Alice", age: 20 >Code language: PHP (php)

In practice, you would select data from a database and use the json_encode() function to convert it to the JSON data.

Converting JSON data to PHP variables

To convert JSON data to a variable in PHP, you use the json_decode() function:

json_decode ( string $json , bool|null $associative = null , int $depth = 512 , int $flags = 0 ) : mixedCode language: PHP (php)

The following example shows how to use json_decode() function to convert JSON data to a variable in PHP:

 $json_data = ''; $person = json_decode($json_data); var_dump($person);Code language: PHP (php)
object(stdClass)#1 (2) ["name"] => string(5) "Alice" ["age"] => int(20) > Code language: PHP (php)

In this example, the json_decode() function converts an object in JSON to an object in PHP. The object is an instance of the stdClass class. To convert JSON data to an object of a specific class, you need to manually map the JSON key/value pairs to object properties. Or you can use a third-party package.

Serializing PHP objects

To serialize an object to JSON data, you need to implement the JsonSerializable interface. The JsonSerializable interface has the jsonSerialize() method that specifies the JSON representation of the object.

For example, the following shows how to implement the JsonSerializable interface and use the json_encode() function to serialize the object:

 class Person implements JsonSerializable < private $name; private $age; public function __construct(string $name, int $age) < $this->name = $name; $this->age = $age; > public function jsonSerialize() < return [ 'name' => $this->name, 'age' => $this->age ]; > > // serialize object to json $alice = new Person('Alice', 20); echo json_encode($alice);Code language: PHP (php)
"name":"Alice","age":20>Code language: PHP (php)
  • First, define a Person class that implements the JsonSerializable interface.
  • Second, return an array that consists of name and age properties from the jsonSerialize() method. The json_encode() function will use the return value of this method to create JSON data.
  • Third, create a new Person object and serialize it to JSON data using the json_encode() function.

Summary

  • JSON is a lightweight data-interchange format.
  • Use the json_encode() function to convert PHP variables to JSON.
  • Use the json_decode() function to convert JSON data to PHP variables.
  • Implement the JsonSerializable interface to specify the JSON representation of an object.

Источник

Читайте также:  Css page break after always
Оцените статью