stlswm / json-object
php json parse to object
v2.2
2019-11-05 09:04 UTC
Requires
- php: >=7.0
- ext-json: *
Requires (Dev)
- phpunit/phpunit: ^8.1
README
Description
php解析json格式字符串到指定的对象中
Software Architecture
php解析json格式字符串到指定的对象中,实现json的强类型解析。
Installation
composer require stlswm/json-object
Instructions
应用举例
一、json编码
<?php
use stlswm\JsonObject\Json;
//Json::marshal($value, int $options = 0, int $depth = 512);
二、json返编码
2.1、类型定义
规则:
1、继承stlswm\JsonObject\ClassMap
2、申明所有属性
3、如果属性是对象或数据则要重写getClassMap申明目标对象
属性是对象:
/**
* @return array
*/
public function getClassMap(): array
{
return [
'data' => InvoiceCreateDataRes::class,
];
}
属性是一维数组:
/**
* @return array
*/
public function getClassMap(): array
{
return [
'data' => [
InvoiceCreateDataRes::class
],
];
}
属性是二维数组:
/**
* @return array
*/
public function getClassMap(): array
{
return [
'data' => [
[
InvoiceCreateDataRes::class
]
],
];
}
以此类推
类申明举例
<?php
namespace stlswm\PiaoZone\Response;
use stlswm\JsonObject\ClassMap;
/**
* Class InvoiceCreateReq
*
* @package stlswm\PiaoZone\Response
*/
class InvoiceCreateRes extends ClassMap
{
//先申明所有属性
/**
* @var string
*/
public $name;
/**
* @var int
*/
public $sex;
/**
* @var stdClass
*/
public $data;
/**
* @return array data为对象在getClassMap中申明data的源对象名称
*/
public function getClassMap(): array
{
return [
'data' => InvoiceCreateDataRes::class,
];
}
}
2.2、json字符串反解析用法
应用举例:
<?php
namespace stlswm\PiaoZone\Business;
use Exception;
use GuzzleHttp\Exception\GuzzleException;
use stlswm\JsonObject\Json;
use stlswm\PiaoZone\Client;
use stlswm\PiaoZone\Request\AccessTokenReq;
use stlswm\PiaoZone\Response\AccessTokenRes;
/**
* Class AccessToken
*
* @package stlswm\PiaoZone\AccessToken
*/
class AccessToken
{
/**
* @param Client $client
* @param AccessTokenReq $accessTokenReq
*
* @return AccessTokenRes
* @throws GuzzleException
* @throws Exception
*/
public static function req(Client $client, AccessTokenReq $accessTokenReq): AccessTokenRes
{
$accessTokenRes = new AccessTokenRes;
$response = $client->request('/base/oauth/token', $accessTokenReq);
$bool = Json::unMarshal($response, $accessTokenRes);
if (!$bool) {
throw new Exception('无法解析返回:' . $response);
}
return $accessTokenRes;
}
}
三、可参考项目:https://github.com/stlswm/piao_zone 中src/Response中类的写法
Contribution
- Fork the repository
- Create Feat_xxx branch
- Commit your code
- Create Pull Request
Gitee Feature
- You can use Readme_XXX.md to support different languages, such as Readme_en.md, Readme_zh.md
- Gitee blog blog.gitee.com
- Explore open source project https://gitee.com/explore
- The most valuable open source project GVP
- The manual of Gitee https://gitee.com/help
- The most popular members https://gitee.com/gitee-stars/