Read a JSON body
A client sends an order as JSON in the body of a POST request. This program reads the body into
an Order object.
<?nvs// This program reads the JSON body of a request into a class.#[Core\Json\Derive]class Order{ // The body comes from the client, so a text property is `tainted string`. public tainted string $product; public uint $quantity;
public function constructor(tainted string $product, uint $quantity) { $this->product = $product; $this->quantity = $quantity; }}
try { // `jsonAs<Order>` reads the body and returns an `Order`. var $order = Core\Request::jsonAs<Order>(); Core\Response::setStatus(201); echo $order->quantity, ' x ', $order->product, "\n";} catch (ParseError $error) { // A body with a missing or wrong field throws a `ParseError`. Core\Response::setStatus(422); foreach ($error->issues as { path: string, message: string } $issue) { echo $issue->path, ': ', $issue->message, "\n"; }}3 x green teaThe output above is for the body {"product":"green tea","quantity":3}.
#[Core\Json\Derive] lets Novis fill an Order from JSON. Each public property reads the key with
the same name. If a key is missing, or has the wrong type, Core\Request::jsonAs throws a
ParseError. Its issues list has one entry for each wrong field.
Read Core\Request for the other ways to read a request.
