Types and getters
JSONObjectBuilder always returns a JSONObject, but the concrete type depends on the JSON value at the root.
JSONKvpObject
If the root value is a JSON object, the result is a JSONKvpObject.
$json = $builder->fromJsonString('{"id": 42, "name": "Ada"}');
echo $json->getInt("id"), PHP_EOL;
echo $json->getString("name"), PHP_EOL;
JSONKvpObject extends the underlying DataObject, so it also supports:
get()getString()getInt()getFloat()getBool()getDateTime()getArray()getInstance()contains()typeof()asArray()asObject()
Because the object is immutable, methods such as with() return a cloned object rather than modifying the current one.
JSONPrimitive
If the root value is not a JSON object, the builder returns one of the primitive subtypes:
JSONStringPrimitiveJSONIntPrimitiveJSONFloatPrimitiveJSONBoolPrimitiveJSONNullPrimitiveJSONArrayPrimitive
Each of these exposes getPrimitiveValue().
$json = $builder->fromJsonString('"hello"');
echo $json->getPrimitiveValue();
Arrays
Arrays appear in two slightly different ways:
- if the root JSON value is an indexed array, the result is
JSONArrayPrimitive - if an array sits inside a
JSONKvpObject, read it withgetArray()
$json = $builder->fromJsonString('{"tags":["php","json"]}');
print_r($json->getArray("tags", "string"));
Passing the optional second argument to getArray() lets us enforce a type for every item in the array.
$json = $builder->fromJsonString('{"ids":[10521,21042,999991]}');
$ids = $json->getArray("ids", "int");
If an item does not match the requested type, PHP throws a TypeError.
Iterating objects
JSONKvpObject implements Iterator, so we can loop over its keys and values.
foreach($json as $key => $value) {
echo $key, ": ", json_encode($value), PHP_EOL;
}
Converting back to JSON
Every JSONObject can be:
- cast to a string, which returns JSON text
- passed to
json_encode() - converted to arrays with
asArray() - converted to
stdClassstyle objects withasObject()
echo (string)$json;
echo json_encode($json);
If you want more background on immutability and the shared getter API, the fuller explanation lives in the PHP.GT/DataObject documentation.
Next, read JSONDocument to see how this package can be used to build JSON output as well as read it.