{"id":23960496,"url":"https://github.com/s-mcdonald/phpjson","last_synced_at":"2025-10-10T13:42:29.482Z","repository":{"id":270529034,"uuid":"910660511","full_name":"s-mcdonald/PHPJson","owner":"s-mcdonald","description":"A Fast and Lightweight PHP JSON Object Serialization Library","archived":false,"fork":false,"pushed_at":"2025-09-15T03:26:08.000Z","size":299,"stargazers_count":1,"open_issues_count":3,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-09-19T18:49:46.588Z","etag":null,"topics":["json","php","serialization"],"latest_commit_sha":null,"homepage":"","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/s-mcdonald.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":"SECURITY.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null},"funding":{"github":"s-mcdonald"}},"created_at":"2025-01-01T01:03:03.000Z","updated_at":"2025-05-31T06:38:31.000Z","dependencies_parsed_at":"2025-04-13T09:31:45.494Z","dependency_job_id":"c84adb07-a5f6-467f-b7f3-8cad01788a6f","html_url":"https://github.com/s-mcdonald/PHPJson","commit_stats":null,"previous_names":["s-mcdonald/json","s-mcdonald/phpjson"],"tags_count":17,"template":false,"template_full_name":null,"purl":"pkg:github/s-mcdonald/PHPJson","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/s-mcdonald%2FPHPJson","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/s-mcdonald%2FPHPJson/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/s-mcdonald%2FPHPJson/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/s-mcdonald%2FPHPJson/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/s-mcdonald","download_url":"https://codeload.github.com/s-mcdonald/PHPJson/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/s-mcdonald%2FPHPJson/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":279004069,"owners_count":26083667,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-10-10T02:00:06.843Z","response_time":62,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["json","php","serialization"],"created_at":"2025-01-06T19:28:54.207Z","updated_at":"2025-10-10T13:42:29.465Z","avatar_url":"https://github.com/s-mcdonald.png","language":"PHP","funding_links":["https://github.com/sponsors/s-mcdonald"],"categories":[],"sub_categories":[],"readme":"# PHPJson\n[![Source](https://img.shields.io/badge/source-S_McDonald-blue.svg)](https://github.com/s-mcdonald/Json)\n![License](https://img.shields.io/github/license/s-mcdonald/phpjson)\n![PHP Compatibility](https://img.shields.io/badge/php-%3E%3D8.2.0-blue)\n\n![Master Build Status](https://img.shields.io/github/actions/workflow/status/s-mcdonald/phpjson/php.yml?branch=master\u0026label=master)\n![Develop Build Status](https://img.shields.io/github/actions/workflow/status/s-mcdonald/phpjson/php.yml?branch=develop\u0026label=develop)\n\n[![Coverage Status](https://coveralls.io/repos/github/s-mcdonald/PHPJson/badge.svg?branch=develop)](https://coveralls.io/github/s-mcdonald/PHPJson?branch=develop)\n\n_A Fast and Lightweight PHP JSON Object Serialization Library._\n\n## 💖 Support This Project\n`PHPJson` is supported by your donations! Click the **[Sponsor](https://github.com/sponsors/s-mcdonald)** link to display funding options.\n\n___\n\n`PHPJson` is a library that provides tools to work with JSON files and structures for PHP.\nIts primary feature is the ability to quickly and easily serialize PHP objects into JSON and deserialize (hydrate) JSON back to PHP objects. \n\nOther features include\n- Encode\n- Decode\n- Minify (uglify)\n- Prettify\n- Json Builder\n- Serialization (including Enums)\n- Serialization value casting\n- Hydration\n- Validation\n\n## Project Objectives\n1. Simplify working with JSON structures.\n2. Enable fast and minimal-configuration serialization using attributes.\n3. Provide advanced serialization capabilities through traits and custom normalizers.\n4. Reduce duplication in business logic by streamlining common tasks.\n\n\n## Contents\n\n* [Usage](#Usage)\n  * [Serialization](#serialization)\n    * [Basic usage](#quick-usage)\n    * [Override Json Properties](#override-json-properties)\n    * [Nested Structures](#nested-structures)\n    * [Serializing Enums](#serializing-enums)\n    * [Casting values](#casting-values)\n  * [Hydration/Deserialization](#deserialize-aka-object-hydration)\n    * [Basic Hydration](#basic-hydration)\n    * [Hydration with Setter Methods](#hydration-with-setter-methods)\n  * [JsonBuilder](#jsonbuilder)\n    * [Basic Builder](#jsonbuilder-basics)\n    * [Objects and Arrays](#jsonbuilder-objects-and-arrays)\n  * [Json Formatting](#json-formatting)\n    * [Prettify](#prettify--Uglify)\n  * [Json Validate](#json-validate)\n* [Installation](#installation)\n* [Dependencies](#dependencies)\n* [License](#license)\n* [Contribute](#contribute)\n\n# Usage\n\n### Serialization\n\n#### Quick usage\nThe fastest way to serialize a class into JSON is by using the `JsonProperty` attribute.\n```php\nclass User\n{\n    #[JsonProperty]\n    public string $name;\n\n    #[JsonProperty]\n    public array $phoneNumbers;    \n    \n    private int $creditCard;\n}\n```\n```json\n{\n    \"name\": \"Foo\",\n    \"phoneNumbers\": [\n        \"044455444\",\n        \"244755465\"\n    ]\n}\n```\n```php\n$serializer = new JsonSerializer();\necho $serializer-\u003eserialize($user);\n```\n\nOr you can use the Json facade\n```php\necho Json::serialize($user); // outputs json\n```\n\n#### Override Json Properties\nYou can customize property names in the JSON output by specifying your own names. This also applies when hydrating objects from JSON.\n\n```php\nclass User\n{\n    #[JsonProperty('userName')]\n    public string $name;\n\n    #[JsonProperty('numbers')]\n    public array $phoneNumbers;    \n    \n    private int $creditCard;\n}\n```\n```json\n{\n    \"userName\": \"Foo\",\n    \"numbers\": [\n        \"044455444\",\n        \"244755465\"\n    ]\n}\n```\n\n#### Serialize from methods\nYou can serialize values from getter methods, regardless of whether the method is public, protected, or private. `PHPJson` will automatically extract the value.\n\n```php\nclass User\n{\n    #[JsonProperty]\n    public function authenticator(): string\n    {\n        return $this-\u003eauthenticator;\n    }\n    \n    #[JsonProperty('creditCardNumber')]\n    public function getCreditCard(): int\n    {\n        return $this-\u003ecreditCard;\n    }\n}\n```\n```json\n{\n    \"authenticator\": \"MasterCard\",\n    \"creditCardNumber\": \"55044455444677\"\n}\n```\n\n#### Nested Structures\n\n`PHPJson` allows you to work seamlessly with complex, nested objects. Nested classes and their properties are serialized into valid JSON structures, matching the relationships between objects.\n\n\n```php\nclass ParentClass\n{\n    #[JsonProperty('userName')]\n    public string $name;\n\n    #[JsonProperty('child')]\n    public ChildClass $someChild;\n}\n\nclass ChildClass\n{\n    public function __construct(\n        #[JsonProperty('childProp')]\n        private string $childProperty,\n    ){\n    }\n}\n```\n```php\n$sut = new ParentClass();\n$sut-\u003ename = 'fu';\n$sut-\u003esomeChild = new ChildClass(\"bar\");\n```\n```json\n{\n    \"userName\": \"fu\",\n    \"child\": {\n        \"childProp\": \"bar\"\n    }\n}\n```\n\n#### Serialization Using a trait\nThe above method utilizes the JsonProperty to serialize any object. This is by far the easiest and fasted way to convert your objects into Json. However, this will have some limitations. To overcome this, we have included two Facets called `SerializesWithMapping` and `SerializesToJson`.  With these Facets you can customize the Serialization and export vastly more complex objects.\n\n\n#### Serializing Enums\n\n`PHPJson` supports the serialization of both pure and backed enums.\n\nPure Enum\n```php\nenum Status \n{\n    case Enabled;\n    case Disabled;\n}\n\necho Json::serialize(Status::Enabled);\n```\n```json\n{\n    \"Status\": \"Enabled\"\n}\n```\n\nBacked Enum\n```php\nenum Status: int\n{\n    case Enabled = 10;\n    case Disabled = 20;\n}\n\necho Json::serialize(Status::Enabled);\n```\n```json\n{\n    \"Status\": 10\n}\n```\n\n#### Casting Values\n\nWhen serializing a PHP object to JSON, you might need to cast specific property values into different types for the JSON output. You can achieve this by using the `JsonProperty` attribute to specify the desired type using a `JsonType`, such as `StringType` or `IntegerType`.\n\n```php\nclass \n{\n    #[JsonProperty(type: new StringType())]\n    public float $myNumber = 123.456;\n    \n    #[JsonProperty(type: new IntegerType())]\n    public float $myNumber2 = 123.456;\n}\n```\n```json\n{\n  \"myNumber\": \"123.456\",\n  \"myNumber2\": 123\n}\n```\n\nAvailable types are;\n  * StringType\n  * ArrayType,\n  * BooleanType,\n  * DoubleType,\n  * IntegerType,\n  * NullType,\n  * ObjectType\n\n\n\n### Deserialize aka Object Hydration\n#### Basic Hydration\nWith `PHPJson`, basic object hydration is straightforward. If your class properties match the structure and property names in your JSON, no additional attributes or mappings are required. The library will automatically map the JSON data to your class or entity.\n\n\n```php\nclass MyUser \n{\n    public string $name;\n    public int $age;\n    public bool $isActive;\n}\n```\n```json\n{\n  \"name\": \"Freddy\",\n  \"age\": 35,\n  \"isActive\": true\n}\n```\n\nNow deserialize the json string with the PHP class.\n```php\n$myUser = Json::deserialize($json, MyUser::class);\n```\n```\nYourNamespace\\MyUser Object (\n    'name' =\u003e 'Freddy'\n    'age' =\u003e 35\n    'isActive' =\u003e true\n)\n```\n\n#### Hydration with Setter Methods\n\nIf your class relies on setters for processing or assigning values, `PHPJson` can hydrate using setter methods, provided these conditions are met:\n\n- The setter accepts exactly one required argument.\n- The `JsonProperty` attribute is used to specify the property for hydration.\n- The argument type matches the data type in the JSON.\n- \n```php\nclass MyUser \n{\n    #[JsonProperty('name')]\n    public string $userName;\n\n    public int $age;\n    public bool $isActive;\n    \n    #[JsonProperty('name')]\n    public function setUserName(string $value): void\n    {\n        $this-\u003euserName = 'foo: ' . $value;\n    }\n}\n```\nNotice how the JsonProperty is used twice here, for hydration setter methods will be the preferred hydration point, since, `setUserName` can not be used for serialization, the property `$userName` will be used for this.\n\n### JsonBuilder\nFluently create Json objects using PHP.\n\n#### JsonBuilder Basics\n```php\n\n$builder = Json::createJsonBuilder()\n        -\u003eaddProperty('id', 11)\n        -\u003eaddProperty('title', \"Apple iOS 15\")\n        -\u003eaddProperty('rating', 4.26)\n        -\u003eaddProperty('stock', 65);\n\necho $builder;\n```\n```json\n{\n    \"id\": 11,\n    \"title\": \"Apple iOS 15\",\n    \"rating\": 4.26,\n    \"stock\": 65\n}\n```\n\n#### JsonBuilder Objects and Arrays\n\n```php\n\n$builder = Json::createJsonBuilder()\n        -\u003eaddProperty('id', 11)\n        -\u003eaddProperty('title', \"Apple iOS 15\")\n        -\u003eaddProperty('rating', 4.26)\n        -\u003eaddProperty('stock', 65);\n        \n        \necho $builder-\u003eaddProperty(\n            'thumbnail',\n            Json::createJsonBuilder()\n                -\u003eaddProperty(\"url\", \"https://i.dummyjson.com/data/products/11/thumbnail.jpg\")\n                -\u003eaddProperty(\"title\", \"thumbnail.jpg\")\n        )\n        -\u003eaddProperty(\"images\", [\n            \"https://i.dummyjson.com/data/products/11/1.jpg\",\n            \"https://i.dummyjson.com/data/products/11/2.jpg\"\n        ])\n;\n```\n```json\n{\n    \"id\": 11,\n    \"title\": \"Apple iOS 15\",\n    \"rating\": 4.26,\n    \"stock\": 65,\n    \"thumbnail\": {\n    \"url\": \"https://i.dummyjson.com/data/products/11/thumbnail.jpg\",\n          \"title\": \"thumbnail.jpg\"\n    },\n    \"images\": [\n          \"https://i.dummyjson.com/data/products/11/1.jpg\",\n          \"https://i.dummyjson.com/data/products/11/2.jpg\"\n     ]\n}\n```\n\n### Json Formatting\n\n#### Prettify \u0026 Uglify\nPrettify or Uglify(minify) your json values\n\n```php\nJson::prettify('{\"name\":\"bar\",\"age\":34}')\n```\n```json\n{\n    \"name\": \"bar\",\n    \"age\": 34\n}\n```\nand then the reverse\n```php\nJson::uglify('{\n    \"name\": \"bar\",\n    \"age\": 34\n}') \n```\n```json\n{\"name\":\"bar\",\"age\":34}\n```\n\n#### Json Validate\nPHP 8.3 onwards has the json_validate function. This library duplicates this behaviour so it can bve used in PHP 8.2\n\n```php\nJson::validate($json): bool\n\n// or\njson_validate($json): bool \n```\n\n# Reference\n\n## Installation\nInstall this package via composer, or simply fork/clone the repo.\n```bash\ncomposer require s-mcdonald/phpjson\n```\n\n## Dependencies\n\n*  None\n\n## PHP Versions\n\n*  PHP 8.2, 8.3, 8.4\n\n## License\n\nJson is licensed under the terms of the [MIT License](http://opensource.org/licenses/MIT)\n(See LICENSE file for details).\n\n## Contribute\n🙌 Want to contribute? \n\nCheck out the issues section to get started.\n\n[![Sponsor](https://img.shields.io/badge/Sponsor-❤-ff69b4)](https://github.com/sponsors/s-mcdonald)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fs-mcdonald%2Fphpjson","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fs-mcdonald%2Fphpjson","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fs-mcdonald%2Fphpjson/lists"}