Skip to content

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.

Available Getters

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.

Example Usage

$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.