kaasplootz / object-parser

使用两个函数即可将对象解析为JSON,反之亦然。

1.2.1 2022-03-02 20:04 UTC

This package is auto-updated.

Last update: 2024-09-29 05:49:08 UTC


README

GitHub stars GitHub issues GitHub license Packagist Version

示例

PHP8对象到JSON

<?php

namespace example;

use kaasplootz\objectParser\ObjectParser;

class SameName extends ObjectParser {}
class Friend extends ObjectParser {}

class User extends ObjectParser {
    public function __construct(
        public int $id,
        public string $username,
        private string $private,
        public float $float,
        public SameName $sameName,
        public SameName $otherName,
        public array $friends,
        public ?string $nullable = null
    ) {}

    public function getPrivate(): string
    {
        return $this->private;
    }
}

$user = new User(
    1,
    'username',
    'privateValue',
    1.0,
    new SameName(),
    new SameName(),
    [
        new Friend()
    ]
);

echo $user->toJSON();

JSON结果

{
  "id": 1,
  "username": "username",
  "private": "privateValue",
  "float": 1,
  "SameName": {},
  "otherName": {
    "SameName": {}
  },
  "friends": [
    {
      "Friend": {}
    }
  ],
  "nullable": null
}

不要惊讶:JSON无法存储x.0为浮点数

JSON到对象

<?php

/* @var User $user */
$user = User::fromJSON('
    {
        "id": 1,
        ...
    }
');

echo $userObject->getPrivate();
// privateValue