cruxoft/bolt-json

基于 Bolt 框架构建的 JSON 封装库

0.4.0 2021-06-24 13:44 UTC

This package is auto-updated.

Last update: 2024-09-24 21:14:02 UTC


README

这是什么?

一个简单的 PHP 中处理 JSON 的封装,内置错误处理。

安装

可以使用 composer 安装,运行以下命令

$ composer require cruxoft/bolt-json

使用

简单的使用涉及调用静态 encodedecode 方法,但是已经包含了面向对象的接口的初步工作。

编码

use Bolt\Json;

try
{
    $json = Json::encode(array("hello" => "world"));
}
catch (\Exception $exception)
{
    die($exception->getMessage());
}

var_dump($json);

输出

string(17) "{"hello":"world"}"

解码

use Bolt\Json;

try
{
    $json = Json::decode('{"hello":"world"}');
}
catch (\Exception $exception)
{
    die($exception->getMessage());
}

var_dump($json);

输出

object(stdClass)#3 (1) {
  ["hello"]=>
  string(5) "world"
}

验证

use Bolt\Json;

var_dump(Json::validate('{"hello":"world"}'));
var_dump(Json::validate('{"hello":"world"x}'));

输出

bool(true)
bool(false)

面向对象

类构造函数接受编码或解码的数据,并允许操作数据和输出。

仍在进行中。

use Bolt\Json;

$json = new Json(array("hello" => "world"));
var_dump($json->toString());