phpgt/json
Composer 安装命令:
composer require phpgt/json
包简介
Structured, type-safe, immutable JSON objects.
README 文档
README
Built on top of PHP.Gt/DataObject, this repository adds JSON-specific compatibility. The main usage will be via the JSONObjectBuilder class that can be used to build a type of JSONObject from a JSON string or decoded JSON object (from json_decode).
The purpose of using these classes to represent decoded JSON data is to provide a type-safe, immutable interface to the enclosed data.
The abstract JSONObject class extends the DataObject base class to represent the root element of a JSON object. In JSON, this may not necessarily be a key-value-pair object.
The following JSON strings can all be successfully decoded:
{"type": "key-value-pair"}- a typical key-value-pair object[{"name": "first"}, {"name": "second"}- an array of objects0- an integer1.05- a floating pointfalse- a boolean"Today is going to be a good day"- a stringnull- a null
Because of this, the base DataObject would be unable to represent the different types of scalar value in a type-safe way. The JSONObjectBuilder class returns a new instance of the abstract JSONObject class which is one of the following types:
JSONKvpObject- identical features toDataObjectwith type-safe getters for its keysJSONPrimitive- a representation of the primitive value, further broken down into typesJSONArrayPrimitive,JSONBoolPrimitive,JSONFloatPrimitive,JSONIntPrimitive,JSONNullPrimitiveandJSONStringPrimitive.
Usage example
use GT\Json\JSONObjectBuilder; use GT\Json\JSONKvpObject; use GT\Json\JSONPrimitive\JSONPrimitive; $response = file_get_contents("https://example.com/details.json"); $builder = new JSONObjectBuilder(); $jsonObject = $builder->fromJsonString($response); if($jsonObject instanceof JSONKvpObject) { $id = $jsonObject->getInt("id"); } elseif($jsonObject instanceof JSONPrimitive) { $id = $jsonObject->getPrimitiveValue(); } echo "Requested ID is: $id";
Fetch API
Check out the PHP implementation of the Fetch API that uses this library to work with JSON endpoints asynchronously.
Proudly sponsored by
统计信息
- 总下载量: 12.45k
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 1
- 点击次数: 0
- 依赖项目数: 5
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2021-01-18