karriere/json-decoder 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

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

karriere/json-decoder

Composer 安装命令:

composer require karriere/json-decoder

包简介

JsonDecoder implementation that allows you to convert your JSON data into PHP class objects

关键字:

README 文档

README

    Packagist Downloads

JsonDecoder for PHP

This package contains a JsonDecoder implementation that allows you to convert your JSON data into php class objects other than stdclass.

Installation

You can install the package via composer

composer require karriere/json-decoder

Usage

By default the Decoder will iterate over all JSON fields defined and will try to set this values on the given class type instance. This change in behavior allows the use of json-decoder on classes that use the magic __get and __set functions like Laravel's Eloquent models.

If a property equally named like the JSON field is found or a explicit Binding is defined for the JSON field it will be decoded into the defined place. Otherwise the property will just be created and assigned (you need the #[AllowDynamicProperties] attribute if you are on PHP 8.2.).

The JsonDecoder class can receive one parameter called shouldAutoCase. If set to true it will try to find the camel-case version from either snake-case or kebap-case automatically if no other binding was registered for the field and it will use an AliasBinding if one of the variants can be found.

A simple example

Assume you have a class Person that looks like this:

#[AllowDynamicProperties]
class Person
{
    public int $id;
    public string $name;
    public ?string $lastname = '';
}

The following code will transform the given JSON data into an instance of Person.

$jsonDecoder = new JsonDecoder();
$jsonData = '{"id": 1, "name": "John Doe", "lastname": null, "dynamicProperty": "foo"}';

$person = $jsonDecoder->decode($jsonData, Person::class);

Please be aware that since PHP 8.2. dynamic properties are deprecated. So if you still wish to have the ability to make use of those dynamic properties you have to add the PHP attribute AllowDynamicProperties to your class. If you are using PHP 8.2. (and greater) and don't use the AllowDynamicProperties attribute all dynamic properties will be ignored.

More complex use case

Let's extend the previous example with a property called address. This address field should contain an instance of Address. As of version 4 you can use the introduced method scanAndRegister to automatically generate the transformer based on class annotations. Since version 5 you can also make use of the property type instead of a class annotation.

class Person
{
    public int $id;
    public string $name;

    /**
     * @var Address
     */
    public $address;
    
    public ?Address $typedAddress = null;
}

For this class definition we can decode JSON data as follows:

$jsonDecoder = new JsonDecoder();
$jsonDecoder->scanAndRegister(Person::class);

$jsonData = '{"id": 1, "name": "John Doe", "address": {"street": "Samplestreet", "city": "Samplecity"}, , "typedAddress": {"street": "Samplestreet", "city": "Samplecity"}}';

$person = $jsonDecoder->decode($jsonData, Person::class);

Defining a Transformer

If you don't use annotations or need a more flexible Transformer you can also create a custom transformer. Let's look at the previous example without annotation.

class Person
{
    public int $id;
    public string $name;
    public mixed $address;
}

To be able to transform the address data into an Address class object you need to define a transformer for Person:

The transformer interface defines two methods:

  • register: here you register your field, array, alias and callback bindings
  • transforms: gives you the full qualified class name e.g.: Your\Namespace\Class
class PersonTransformer implements Transformer
{
    public function register(ClassBindings $classBindings)
    {
        $classBindings->register(new FieldBinding('address', 'address', Address::class));
    }

    public function transforms()
    {
        return Person::class;
    }
}

After registering the transformer the JsonDecoder will use the defined transformer:

$jsonDecoder = new JsonDecoder();
$jsonDecoder->register(new PersonTransformer());

$jsonData = '{"id": 1, "name": "John Doe"}';

$person = $jsonDecoder->decode($jsonData, Person::class);

Handling private and protected properties

As of version 4 the JsonDecoder class will handle private and protected properties out of the box.

Transforming an array of elements

If your JSON contains an array of elements at the root level you can use the decodeMultiple method to transform the JSON data into an array of class type objects.

$jsonDecoder = new JsonDecoder();

$jsonData = '[{"id": 1, "name": "John Doe"}, {"id": 2, "name": "Jane Doe"}]';

$personArray = $jsonDecoder->decodeMultiple($jsonData, Person::class);

Documentation

Transformer Bindings

The following Binding implementations are available

FieldBinding

Defines a JSON field to property binding for the given type.

Signature:

new FieldBinding(string $property, ?string $jsonField = null, ?string $type = null, bool $isRequired = false);

This defines a field mapping for the property $property to a class instance of type $type with data in $jsonField.

ArrayBinding

Defines an array field binding for the given type.

Signature:

new ArrayBinding(string $property, ?string $jsonField = null, ?string $type = null, bool $isRequired = false);

This defines a field mapping for the property $property to an array of class instance of type $type with data in $jsonField.

AliasBinding

Defines a JSON field to property binding.

Signature:

new AliasBinding(string $property, ?string $jsonField = null, bool $isRequired = false);

DateTimeBinding

Defines a JSON field to property binding and converts the given string to a DateTime instance.

Signature:

new DateTimeBinding(string $property, ?string $jsonField = null, bool $isRequired = false, $dateTimeFormat = DateTime::ATOM);

CallbackBinding

Defines a property binding that gets the callback result set as its value.

Signature:

new CallbackBinding(string $property, private Closure $callback);

License

Apache License 2.0 Please see LICENSE for more information.

karriere/json-decoder 适用场景与选型建议

karriere/json-decoder 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 443.45k 次下载、GitHub Stars 达 140, 最近一次更新时间为 2017 年 04 月 24 日, 在 PHP 生态内属于活跃度较高的组件。

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

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

围绕 karriere/json-decoder 我们能提供哪些服务?
定制开发 / 二次开发

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

  • 总下载量: 443.45k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 141
  • 点击次数: 10
  • 依赖项目数: 13
  • 推荐数: 0

GitHub 信息

  • Stars: 140
  • Watchers: 12
  • Forks: 23
  • 开发语言: PHP

其他信息

  • 授权协议: Apache-2.0
  • 更新时间: 2017-04-24