greenskies / json
改进的 PHP JSON 库
0.2.0
2019-03-08 00:04 UTC
Requires
- ext-json: *
- justinrainbow/json-schema: ^5.2
- karriere/json-decoder: ^2.2
- symfony/options-resolver: ^4.2
Requires (Dev)
- php-coveralls/php-coveralls: ^2.1
- phpunit/phpunit: ^7.0 | ^8.0
This package is auto-updated.
Last update: 2024-09-08 16:04:21 UTC
README
Greenskies Json
一个用于改进解码的 PHP 库 - 包括模式验证和解码到类
它基本上是 karriereat/json-decoder 的封装
- karriereat/json-decoder
- justinrainbow/json-schema 带有一点语法糖和异常处理,甚至在 PHP < 7.3 上也能使用
安装
composer require greenskies/json
解码
要解码 JSON 字符串,只需将字符串传递给 Json::Decode()
,这将返回一个标准对象
$jsonString = '{"good":true}'; $decoded = Json::Decode($jsonString); // $decoded->good = true
$jsonString = '{"good":true}'; $options = [ Json::ASSOCIATIVE => true, ]; $decoded = Json::Decode($jsonString, $options); // $decoded['good'] = true
模式验证
$jsonString = '{"processRefund": "true", "refundAmount": "17"}' $schema = (object) [ "type"=>"object", "properties"=>(object)[ "processRefund"=>(object)[ "type"=>"boolean" ], "refundAmount"=>(object)[ "type"=>"number" ] ] ]; $options = [ Json::VALIDATOR => [ Json::JSON_SCHEMA => $schema, Json::CONSTRAINTS => Constraint::CHECK_MODE_COERCE_TYPES, ], ]; $decoded = Json::Decode($jsonString, $options);
有关进一步说明,请访问 justinrainbow/json-schema
解码到类
$jsonString = '{"id": 1, "name": "John Doe"}'; $options = [ Json::DECODER => [ Json::CLASS_NAME => Person::class, ], ]; $decoded = Json::Decode($jsonString, $options);
解码多个
$jsonString = '[{"id": 1, "name": "John Doe"}, {"id": 2, "name": "Jane Doe"}]'; $options = [ Json::DECODER => [ Json::CLASS_NAME => Person::class, Json::DECODE_MULTIPLE => true, ], ]; $personArray = Json::Decode($jsonString, $options);
有关进一步说明,请访问 karriereat/json-decoder