Core\Json::decodeAs
Core\Json::decodeAs<T>(string $json, {maxDepth?: uint}): TCore\Json::decodeAs<T>( string $json, {maxDepth?: uint}, ): T
Core\Json::decodeAs<User>($text) reads a JSON object and returns a new instance of your class User. Write array<User> to read a JSON array of objects.
The class needs the #[Core\Json\Derive] attribute, and each public property reads the key with the same name. A class inside an object type such as {user: User}, or inside an array type, needs the attribute too. The compiler checks this. A property with a default value is optional: with ?string $city = null, a missing city key gives null.
A property can also be a time value or a Core\Uuid, written as a JSON string. A date is its ISO text, such as "2026-05-14". A DateTime needs its time zone, as in "2026-05-14T08:30:00+02:00[Europe/Vienna]".
Text that is not valid JSON, or a missing or wrong field, throws a ParseError. Its issues list has one entry for each wrong field, up to 64. The constructor runs only when all fields are correct.
The examples below read one object, show the error for two wrong fields, read a list of orders, and read time values and an id.
Parameters
$jsonstringThe JSON text to parse. Its top level must be an object. WhenTis written asarray<C>, its top level must be an array.
Options
maxDepthuintoptionalThe deepest nesting allowed. A scalar document is depth 1, and[1]is depth 2. The default is512, and the largest value is1024.
Return value
Returns T. A new T created from the fields of the document. For an array<C>, it is one new C per element, in the order of the document.
Errors
ParseErrorWhen$jsonis not a valid JSON document, or nests deeper thanmaxDepth. When it has an object with the same key twice, or a whole number too large forint. When the top level is not an object, or not an array for anarray<C>. When fields are missing or have the wrong type. The error has a list of issues, one for each wrong field. A list inside the object gets one issue for each wrong element. Each issue has a path, such asitems.2.price, and a message. The error message gives the number of issues. When the whole document is read as anarray<C>, the decode stops at the first bad element. The issues are then the wrong fields of that element. The list has at most 64 issues. When there are more, the last issue says so, and its path is the empty string.LogicErrorTcannot be read from JSON because it does not have#[Json\Derive]. It is also thrown whenmaxDepthis0or above1024.RecursionErrorThe call stack has no more room when a constructor is called. This happens when a constructor calls itself many times, or whendecodeAsis called from deep recursion. A deeply nested document withinmaxDepthdoes not throw this error.
Changelog
| Version | Change |
|---|---|
0.0.5 | Core\Json::decodeAs matches each key with less work and finds each class's constructor once per call. Decoding a list of objects allocates only the objects and their strings. |
0.0.6 | A Core\Time\Date, TimeOfDay, DateTime, Duration, Zone or Core\Uuid is now a JSON string, as Instant already was. A time zone is written as its name, such as "Europe/Vienna". A text that is not valid throws a ParseError that names its key. |
0.0.6 | Some decoders take a type, such as Core\Json::decodeAs and Core\Request::jsonAs. They check every class inside a shape or an array of that type, at any depth. Core\Request::jsonAs, queryParametersAs and formFieldsAs give the error E0810 when such a class has a plain string property. |
0.0.6 | A ParseError from Core\Json::decodeAs lists at most 64 issues. When there are more, the last issue says that more follow. |
Examples
Reading an object into a class
<?nvs// Shows how to read a JSON object straight into an instance of your own class.
// `#[Core\Json\Derive]` gives the class a JSON format. Each public property is one key.// `#[Core\Json\Field]` sets a different key name for one property.#[Core\Json\Derive]class User{ public int $id; #[Core\Json\Field(name: 'display_name')] public string $name; public bool $admin;
public function constructor(int $id, string $name, bool $admin) { $this->id = $id; $this->name = $name; $this->admin = $admin; }}
string $text = "{\"id\":7,\"display_name\":\"Ada\",\"admin\":true}";
// The type between `<` and `>` is the class to create. The result is a `User`,// so you can use its properties without a conversion.var $user = Core\Json::decodeAs<User>($text);
// This prints `7 Ada admin`.echo $user->id, ' ', $user->name, ' ', $user->admin ? 'admin' : 'guest', "\n";7 Ada adminFields that are missing or wrong
<?nvs// Shows the error `Core\Json::decodeAs` throws when the document does not match the class.
#[Core\Json\Derive]class Product{ public string $name; public int $cents;
public function constructor(string $name, int $cents) { $this->name = $name; $this->cents = $cents; }}
// `name` is missing, and `cents` is a string. Both are errors.string $text = "{\"cents\":\"cheap\"}";
// The call throws one `ParseError`. Its `issues` list has one entry for each wrong field,// with the field's path and a message.try { Core\Json::decodeAs<Product>($text); echo "decoded\n";} catch (ParseError $error) { // This prints the number of problems, and then the path and message of each one. echo Core\Arr::count($error->issues), " problems\n"; foreach ($error->issues as { path: string, message: string } $issue) { echo $issue->path, ': ', $issue->message, "\n"; }}2 problemsname: required field missingcents: expected int, found a stringReading a list of orders
<?nvs// Shows a program that reads a list of orders from a JSON API and adds up the unpaid ones.
#[Core\Json\Derive]class Order{ public int $number; public int $cents; public bool $paid;
public function constructor(int $number, int $cents, bool $paid) { $this->number = $number; $this->cents = $cents; $this->paid = $paid; }}
// A shop system sends this text. It is a JSON array with one object for each order.string $body = "[{\"number\":1041,\"cents\":2500,\"paid\":true}," . "{\"number\":1042,\"cents\":1200,\"paid\":false}," . "{\"number\":1043,\"cents\":900,\"paid\":false}]";
// `array<Order>` reads the JSON array. The result has one `Order` for each element.var $orders = Core\Json::decodeAs<array<Order>>($body);
int $open = 0;foreach ($orders as Order $order) { if (!$order->paid) { echo 'order ', $order->number, " is not paid\n"; $open = $open + $order->cents; }}
// This prints `unpaid: 2100 cents`.echo 'unpaid: ', $open, " cents\n";order 1042 is not paidorder 1043 is not paidunpaid: 2100 centsReading dates and durations from text
<?nvs// Shows how a decode reads a date, a duration and an id from JSON strings.
use Core\Json;
// A booking system sends this text. Every value in it is a string.string $body = '{"id":"0190f3a2-7b1c-7def-8a12-3456789abcde","day":"2026-05-14","length":"45m"}';
// Each field type is a `Core` class, so the decode converts each string.var $booking = Json::decodeAs<{ id: Core\Uuid, day: Core\Time\Date, length: Core\Time\Duration }>($body);
// This prints `2026-05-14 0190f3a2-7b1c-7def-8a12-3456789abcde`.echo $booking->day->toIso(), ' ', $booking->id->toString(), "\n";
// This prints `2700 seconds`.echo $booking->length->toSeconds(), " seconds\n";
// A string that is not a valid duration throws a `ParseError`.try { Json::decodeAs<{ length: Core\Time\Duration }>('{"length":"soon"}');} catch (ParseError $bad) { echo $bad->issues['0']->path, ': ', $bad->issues['0']->message, "\n";}2026-05-14 0190f3a2-7b1c-7def-8a12-3456789abcde2700 secondslength: expected a duration as a string such as 1h30m, found a string