承接 s-mcdonald/phpjson 相关项目开发

从需求分析到上线部署,全程专人跟进,保证项目质量与交付效率

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

s-mcdonald/phpjson

Composer 安装命令:

composer require s-mcdonald/phpjson

包简介

PHPJson: An elegant and simple JSON object serialization library for PHP.

README 文档

README

Source License PHP Compatibility

Master Build Status Develop Build Status

Coverage Status

A Fast and Lightweight PHP JSON Object Serialization Library.

💖 Support This Project

PHPJson is supported by your donations! Click the Sponsor link to display funding options.

PHPJson is a library that provides tools to work with JSON files and structures for PHP. Its primary feature is the ability to quickly and easily serialize PHP objects into JSON and deserialize (hydrate) JSON back to PHP objects.

Other features include

  • Encode
  • Decode
  • Minify (uglify)
  • Prettify
  • Json Builder
  • Serialization (including Enums)
  • Serialization value casting
  • Hydration
  • Validation

Project Objectives

  1. Simplify working with JSON structures.
  2. Enable fast and minimal-configuration serialization using attributes.
  3. Provide advanced serialization capabilities through traits and custom normalizers.
  4. Reduce duplication in business logic by streamlining common tasks.

Contents

Usage

Serialization

Quick usage

The fastest way to serialize a class into JSON is by using the JsonProperty attribute.

class User
{
    #[JsonProperty]
    public string $name;

    #[JsonProperty]
    public array $phoneNumbers;    
    
    private int $creditCard;
}
{
    "name": "Foo",
    "phoneNumbers": [
        "044455444",
        "244755465"
    ]
}
$serializer = new JsonSerializer();
echo $serializer->serialize($user);

Or you can use the Json facade

echo Json::serialize($user); // outputs json

Override Json Properties

You can customize property names in the JSON output by specifying your own names. This also applies when hydrating objects from JSON.

class User
{
    #[JsonProperty('userName')]
    public string $name;

    #[JsonProperty('numbers')]
    public array $phoneNumbers;    
    
    private int $creditCard;
}
{
    "userName": "Foo",
    "numbers": [
        "044455444",
        "244755465"
    ]
}

Serialize from methods

You can serialize values from getter methods, regardless of whether the method is public, protected, or private. PHPJson will automatically extract the value.

class User
{
    #[JsonProperty]
    public function authenticator(): string
    {
        return $this->authenticator;
    }
    
    #[JsonProperty('creditCardNumber')]
    public function getCreditCard(): int
    {
        return $this->creditCard;
    }
}
{
    "authenticator": "MasterCard",
    "creditCardNumber": "55044455444677"
}

Nested Structures

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.

class ParentClass
{
    #[JsonProperty('userName')]
    public string $name;

    #[JsonProperty('child')]
    public ChildClass $someChild;
}

class ChildClass
{
    public function __construct(
        #[JsonProperty('childProp')]
        private string $childProperty,
    ){
    }
}
$sut = new ParentClass();
$sut->name = 'fu';
$sut->someChild = new ChildClass("bar");
{
    "userName": "fu",
    "child": {
        "childProp": "bar"
    }
}

Serialization Using a trait

The 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.

Serializing Enums

PHPJson supports the serialization of both pure and backed enums.

Pure Enum

enum Status 
{
    case Enabled;
    case Disabled;
}

echo Json::serialize(Status::Enabled);
{
    "Status": "Enabled"
}

Backed Enum

enum Status: int
{
    case Enabled = 10;
    case Disabled = 20;
}

echo Json::serialize(Status::Enabled);
{
    "Status": 10
}

Casting Values

When 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.

class 
{
    #[JsonProperty(type: new StringType())]
    public float $myNumber = 123.456;
    
    #[JsonProperty(type: new IntegerType())]
    public float $myNumber2 = 123.456;
}
{
  "myNumber": "123.456",
  "myNumber2": 123
}

Available types are;

  • StringType
  • ArrayType,
  • BooleanType,
  • DoubleType,
  • IntegerType,
  • NullType,
  • ObjectType

Deserialize aka Object Hydration

Basic Hydration

With 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.

class MyUser 
{
    public string $name;
    public int $age;
    public bool $isActive;
}
{
  "name": "Freddy",
  "age": 35,
  "isActive": true
}

Now deserialize the json string with the PHP class.

$myUser = Json::deserialize($json, MyUser::class);
YourNamespace\MyUser Object (
    'name' => 'Freddy'
    'age' => 35
    'isActive' => true
)

Hydration with Setter Methods

If your class relies on setters for processing or assigning values, PHPJson can hydrate using setter methods, provided these conditions are met:

  • The setter accepts exactly one required argument.
  • The JsonProperty attribute is used to specify the property for hydration.
  • The argument type matches the data type in the JSON.
class MyUser 
{
    #[JsonProperty('name')]
    public string $userName;

    public int $age;
    public bool $isActive;
    
    #[JsonProperty('name')]
    public function setUserName(string $value): void
    {
        $this->userName = 'foo: ' . $value;
    }
}

Notice 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.

JsonBuilder

Fluently create Json objects using PHP.

JsonBuilder Basics

$builder = Json::createJsonBuilder()
        ->addProperty('id', 11)
        ->addProperty('title', "Apple iOS 15")
        ->addProperty('rating', 4.26)
        ->addProperty('stock', 65);

echo $builder;
{
    "id": 11,
    "title": "Apple iOS 15",
    "rating": 4.26,
    "stock": 65
}

JsonBuilder Objects and Arrays

$builder = Json::createJsonBuilder()
        ->addProperty('id', 11)
        ->addProperty('title', "Apple iOS 15")
        ->addProperty('rating', 4.26)
        ->addProperty('stock', 65);
        
        
echo $builder->addProperty(
            'thumbnail',
            Json::createJsonBuilder()
                ->addProperty("url", "https://i.dummyjson.com/data/products/11/thumbnail.jpg")
                ->addProperty("title", "thumbnail.jpg")
        )
        ->addProperty("images", [
            "https://i.dummyjson.com/data/products/11/1.jpg",
            "https://i.dummyjson.com/data/products/11/2.jpg"
        ])
;
{
    "id": 11,
    "title": "Apple iOS 15",
    "rating": 4.26,
    "stock": 65,
    "thumbnail": {
    "url": "https://i.dummyjson.com/data/products/11/thumbnail.jpg",
          "title": "thumbnail.jpg"
    },
    "images": [
          "https://i.dummyjson.com/data/products/11/1.jpg",
          "https://i.dummyjson.com/data/products/11/2.jpg"
     ]
}

Json Formatting

Prettify & Uglify

Prettify or Uglify(minify) your json values

Json::prettify('{"name":"bar","age":34}')
{
    "name": "bar",
    "age": 34
}

and then the reverse

Json::uglify('{
    "name": "bar",
    "age": 34
}') 
{"name":"bar","age":34}

Json Validate

PHP 8.3 onwards has the json_validate function. This library duplicates this behaviour so it can bve used in PHP 8.2

Json::validate($json): bool

// or
json_validate($json): bool 

Reference

Installation

Install this package via composer, or simply fork/clone the repo.

composer require s-mcdonald/phpjson

Dependencies

  • None

PHP Versions

  • PHP 8.2, 8.3, 8.4

License

Json is licensed under the terms of the MIT License (See LICENSE file for details).

Contribute

🙌 Want to contribute?

Check out the issues section to get started.

Sponsor

s-mcdonald/phpjson 适用场景与选型建议

s-mcdonald/phpjson 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 243 次下载、GitHub Stars 达 1, 最近一次更新时间为 2025 年 01 月 03 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「json」 「serializer」 「hydration」 「json-php」 「php-json」 「php-json-library」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 s-mcdonald/phpjson 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 s-mcdonald/phpjson 我们能提供哪些服务?
定制开发 / 二次开发

基于 s-mcdonald/phpjson 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 243
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 1
  • 点击次数: 20
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 1
  • Watchers: 1
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-01-03