Skip to content

Json Object Builder

Greg Bowler edited this page Mar 1, 2025 · 2 revisions

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.

Creating a JSON Object

JsonObjectBuilder offers multiple methods for constructing JsonObject instances.

From a JSON String

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);

From Decoded JSON

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);

From a File

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");

Supported JSON Types

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.

Why Use JsonObjectBuilder?

  • Ensures type safety and immutability.
  • Prevents malformed JSON from being processed.
  • Automatically selects the correct JsonObject subtype.

Next, we'll cover what is immutability?

Clone this wiki locally