Skip to content
Greg Bowler edited this page Mar 1, 2025 · 7 revisions

Throughout PHP.Gt libraries, wherever an object is used to represent data, the PHP.Gt/DataObject library is used. Instances of DataObject provide structured, type-safe, immutable data transfer.

This library extends DataObject by adding JSON-specific functionality. The primary entry point for this library is the JsonObjectBuilder class which allows developers to construct JsonObject instances from raw JSON strings or decoded JSON data 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. What is immutability?

Beyond serving as a JSON-specific DataObject, this library enables validation against a JSON schema, ensuring that data adheres to expected formats and types. This feature helps detect errors early and enforces data integrity when working with JSON APIs.

Additionally, JsonObjectBuilder simplifies the process of constructing strongly-typed JSON objects by enforcing schema rules at creation. This ensures that developers don't need to manually verify or sanitise JSON input, reducing the risk of runtime errors caused by unexpected data structures.

A typical example

The following JSON string is taken from the Stripe API documentation as example data to work with.

$jsonString = <<<JSON
{
	"object": "balance",
	"available": [
		{
			"amount": 2217713,
			"currency": "cad",
			"source_types": {
				"bank_account": 0,
				"card": 2217713
			}
		},
		{
			"amount": 7254790,
			"currency": "gbp",
			"source_types": {
				"bank_account": 0,
				"card": 7254790
			}
		}
	]
}
JSON;

In this example, we extract and display the object value, then iterate over the available array to print each currency and its formatted amount.

$builder = new JsonObjectBuilder();
$json = $builder->fromJsonString($jsonString);

echo "Type of object: ", $json->getString("object"), PHP_EOL;

/** @var JsonObject $available */
foreach($json->getArray("available") as $available) {
	echo PHP_EOL;
	echo "Currency: ", $available->getString("currency"), PHP_EOL;
	echo "Amount: ", number_format($available->getInt("amount") / 100), PHP_EOL;
}

Internally, the string is parsed with json_decode as usual, but instead of returning generic arrays and objects, it constructs typed JsonObject instances with type-safe getters, ensuring reliability and clarity when accessing data.


In the next section we will list out the type-safe getters and how to use them.

Clone this wiki locally