-
-
Notifications
You must be signed in to change notification settings - Fork 1
Json Object Builder
The JsonObjectBuilder
class provides a structured way to create JsonObject
instances from various sources, including JSON strings, decoded JSON data, and files containing JSON. It ensures that parsed JSON is represented with type safety and immutability.
JsonObjectBuilder
offers multiple methods for constructing JsonObject
instances.
Use fromJsonString()
to parse a JSON string into a JsonObject
. This method ensures valid JSON formatting and throws an exception if parsing fails.
$jsonString = '{"org":"PHP.Gt","repo":"json"}';
$builder = new JsonObjectBuilder();
$json = $builder->fromJsonString($jsonString);
Use fromJsonDecoded()
when working with pre-decoded JSON data. This method handles various JSON types and constructs an appropriate JsonObject
.
$jsonString = '{"org":"PHP.Gt","repo":"json"}';
$jsonDecoded = json_decode($jsonString);
$json = $builder->fromJsonDecoded($jsonDecoded);
Use fromFile()
to read and parse a JSON file. This method ensures that the file exists and throws an exception if it is missing.
$json = $builder->fromFile("/path/to/file.json");
The builder automatically determines the type of JSON data and returns an appropriate subtype of JsonObject
:
-
Key-Value Pairs (
JsonKvpObject
) – Used for objects. -
Primitives (
JsonPrimitive
) – Handles strings, integers, floats, booleans, and null values. -
Arrays (
JsonArrayPrimitive
) – Represents indexed JSON arrays.
- Ensures type safety and immutability.
- Prevents malformed JSON from being processed.
- Automatically selects the correct
JsonObject
subtype.
Next, we'll cover what is immutability?
PHP.Gt/Json is a separately maintained component of PHP.Gt/WebEngine.