VOOZH about

URL: https://www.mediawiki.org/wiki/JsonCodec

⇱ JsonCodec - MediaWiki


Jump to content
From mediawiki.org

JsonCodec is a PHP library that builds on top of PHP's native JsonSerializable interface. It is used to implement JSON serialization and deserialization for custom objects. It was introduced into MediaWiki 1.36 via Gerrit change 641575.

Install

[edit]

To use the package outside of MediaWiki, install the wikimedia/json-codec package from Packagist:

composerrequirewikimedia/json-codec

Usage

[edit]
<?php

use Wikimedia\JsonCodec\JsonCodecable;
use Wikimedia\JsonCodec\JsonCodecableTrait;

class SampleObject implements JsonCodecable {
	use JsonCodecableTrait;

	/** @var string */
	public string $property;

	// ....

	// Implement JsonCodecable using the JsonCodecableTrait

	/** @inheritDoc */
	public function toJsonArray(): array {
		return [
			'property' => $this->property,
		];
	}

	/** @inheritDoc */
	public static function newFromJsonArray( array $json ): SampleObject {
		return new SampleObject( $json['property'] );
	}
}

For more examples, you can read the library's README.md.

External links

[edit]