phpgt / json
Structured, type-safe, immutable JSON objects.
Fund package maintenance!
PhpGt
Installs: 1 310
Dependents: 4
Suggesters: 0
Security: 0
Stars: 0
Watchers: 3
Forks: 1
Open Issues: 3
Requires
- php: >=8.1
- ext-json: *
- phpgt/dataobject: ^1.0.7
Requires (Dev)
- phpmd/phpmd: ^2.13
- phpstan/phpstan: ^1.10
- phpunit/phpunit: ^10.1
- squizlabs/php_codesniffer: ^3.7
This package is auto-updated.
Last update: 2024-11-13 16:07:57 UTC
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 toDataObject
with type-safe getters for its keysJsonPrimitive
- a representation of the primitive value, further broken down into typesJsonArrayPrimitive
,JsonBoolPrimitive
,JsonFloatPrimitive
,JsonIntPrimitive
,JsonNullPrimitive
andJsonStringPrimitive
.
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.