JSON with types
JSON from another program may have a missing field or a field of the wrong type. Core\Json::decodeAs
reads JSON text into an object of a class, and it checks every property:
<?nvs// This program reads JSON text into an object of a class.#[Core\Json\Derive]class Order{ public string $item; public int $count;
public function constructor(string $item, int $count) { $this->item = $item; $this->count = $count; }}
// `Core\Json::decodeAs` checks the JSON against every property of the class.Order $order = Core\Json::decodeAs<Order>('{"item":"tea","count":3}');echo $order->item, ' x ', $order->count, "\n";
// `count` is text here, and the class needs an `int`. The call throws an error.try { Order $bad = Core\Json::decodeAs<Order>('{"item":"tea","count":"many"}');} catch (RuntimeError $e) { echo $e->message, "\n";}tea x 3Core\Json::decodeAs(): 1 value(s) of `Order` did not match#[Core\Json\Derive] on the class is all you write. Novis reads the properties and their types from the
class.
When the JSON does not match the class, the call throws an error. After the call, every property has the type that the class declares.
Read more in Syntax: JSON attributes and
Reference: Core\Json.
