-
-
Notifications
You must be signed in to change notification settings - Fork 1
Type safe getters
Greg Bowler edited this page Mar 1, 2025
·
5 revisions
JsonObject and its subtypes provide a type-safe way to access JSON data, ensuring correct types without manual validation. Instead of handling raw associative arrays, JsonObject guarantees structured and predictable data access.
All subtypes of JsonObject implement the TypeSafeGetter interface, exposing:
-
get(string $name):mixed– Retrieves the raw value. -
getString(string $name):string– Ensures a string value. -
getInt(string $name):int– Ensures an integer. -
getFloat(string $name):float– Ensures a float. -
getBool(string $name):bool– Ensures a boolean. -
getDateTime(string $name):DateTimeInterface– Parses a valid date-time.
If a key is missing or invalid, an exception is thrown for non-nullable types.
$json = $builder->fromJsonString($jsonString);
echo "Object Type: " . $json->getString("object");
foreach ($json->getArray("available") as $available) {
echo "\nCurrency: " . $available->getString("currency");
echo "\nAmount: " . number_format($available->getInt("amount") / 100);
}In the next section, learn how to construct the JsonObject classes using the Json Object Builder.
PHP.Gt/Json is a separately maintained component of PHP.Gt/WebEngine.