Objects as JSON
#[Core\Json\Derive] in front of a class lets you convert its objects to and from JSON.
Core\Json::encode writes an object as JSON text. Core\Json::decodeAs<T> builds an object of
the class T from JSON text.
A Core\Time\Date, TimeOfDay, DateTime, Instant, Duration, Zone or Core\Uuid is a JSON
string. A date is written "2026-03-09", and a time zone is written as its name, such as
"Europe/Vienna". A text that is not valid throws a ParseError. Its issues list names the key.
Core\Json\Derive and Core\Json\Field
#[Core\Json\Derive] on a class gives it a JSON encoder and a JSON decoder. Core\Json::encode then accepts instances of that class, and Core\Json::decodeAs builds one from JSON text.
The fields of the document are the class's properties, in the order they are written. A subclass also has the properties of its parent classes, and they come first. Each property is also a constructor parameter of the same name and type, because a decode calls your constructor. #[Core\Json\Field] renames one property's key or leaves it out.
A property can have a set of allowed values, such as "draft"|"live". A mixed property takes any JSON value. A Date, TimeOfDay, DateTime, Instant, Duration, Zone or Core\Uuid property is written as a JSON string, such as "2026-01-05" or "1h30m".
A decode checks the whole document before it builds anything. If a field is missing or has the wrong type, the decode throws a ParseError. The error lists every bad field at once.
The examples show an encode, a renamed key, a request body and each check of a decode. They also show an enum, a fixed key order, a subclass, a set of allowed values, a mixed property and dates written as strings.
Give a class a json codec
<?nvs// Shows how to turn an object into JSON text. `#[Core\Json\Derive]` on a class// gives it an encoder, so `Core\Json::encode` accepts its instances.
use Core\Json;
#[Core\Json\Derive]class Point{ public int $x; public int $y;
// Every property is a constructor parameter of the same name and type. public function constructor(int $x, int $y) { $this->x = $x; $this->y = $y; }}
// The keys are the declared properties, in the order they are written.// This prints {"x":3,"y":4}.echo Json::encode(new Point(3, 4)), "\n";
#[Core\Json\Derive]class Line{ public Point $from; public Point $to;
public function constructor(Point $from, Point $to) { $this->from = $from; $this->to = $to; }}
// A property whose type is another class with the attribute is encoded inside the// same document. This prints {"from":{"x":0,"y":0},"to":{"x":3,"y":4}}.echo Json::encode(new Line(new Point(0, 0), new Point(3, 4))), "\n";{"x":3,"y":4}{"from":{"x":0,"y":0},"to":{"x":3,"y":4}}Rename a key and skip a property
<?nvs// Shows how to control the keys of a JSON document. `#[Core\Json\Field]` has two// options. `name:` writes a property under a different key, and `skip: true`// leaves it out of the document.
use Core\Json;use Core\Json\Field;
#[Core\Json\Derive]class Article{ public string $title;
// The JSON key is `published_at`, and the property is `$publishedAt`. #[Field(name: 'published_at')] public string $publishedAt;
// A skipped property needs no constructor parameter, and it never appears // in the document. #[Field(skip: true)] public uint $viewCount;
public function constructor(string $title, string $publishedAt) { $this->title = $title; $this->publishedAt = $publishedAt; $this->viewCount = 0; }}
// This prints {"title":"Novis 1.0","published_at":"2026-03-01"}.echo Json::encode(new Article('Novis 1.0', '2026-03-01')), "\n";
// Decoding reads the `published_at` key, and `$viewCount` gets the value the// constructor sets. This prints `2026-03-01 0`.var $article = Json::decodeAs<Article>("{\"title\":\"Novis 1.0\",\"published_at\":\"2026-03-01\"}");echo $article->publishedAt, ' ', $article->viewCount, "\n";{"title":"Novis 1.0","published_at":"2026-03-01"}2026-03-01 0Read a request body into an object
<?nvs// Shows how to read a JSON request body into an object. `Core\Json::decodeAs`// checks the whole document and then calls the class constructor. A bad document// throws a `ParseError` that lists every bad field at once.
use Core\Json;use Core\Json\Field;
#[Core\Json\Derive]class Address{ public string $city;
public function constructor(string $city) { $this->city = $city; }}
#[Core\Json\Derive]class Signup{ public string $email; public uint $age; #[Field(name: 'accepts_mail')] public bool $acceptsMail; public Address $address;
public function constructor(string $email, uint $age, bool $acceptsMail, Address $address) { $this->email = $email; $this->age = $age; $this->acceptsMail = $acceptsMail; $this->address = $address; }}
string $body = "{\"email\":\"ada@example.com\",\"age\":36,\"accepts_mail\":true," . "\"address\":{\"city\":\"london\"},\"sent_at\":\"today\"}";
// A key the class does not declare is ignored, so `sent_at` changes nothing.// This prints `ada@example.com lives in london`.var $signup = Json::decodeAs<Signup>($body);echo $signup->email, ' lives in ', $signup->address->city, "\n";
// Now a body that the client got wrong. The decode builds nothing and throws.try { Json::decodeAs<Signup>("{\"email\":\"ada@example.com\",\"age\":\"old\",\"address\":{}}");} catch (ParseError $bad) { // Each issue names the key it is about. A key inside `address` is written // with the path that reaches it, as `address.city`. foreach ($bad->issues as { path: string, message: string } $issue) { echo $issue->path, ': ', $issue->message, "\n"; }}ada@example.com lives in londonage: expected uint, found a stringaccepts_mail: required field missingaddress.city: required field missingCheck every field of a document
<?nvs// Shows what a decode checks for each property. A `?int` property takes `null`.// A `bool` property does not, so `null` there is an issue.
#[Core\Json\Derive]class Row{ public string $name; public ?int $rank; #[Core\Json\Field(name: 'is_live')] public bool $live;
public function constructor(string $name, ?int $rank, bool $live) { $this->name = $name; $this->rank = $rank; $this->live = $live; }}
// The key `extra` is not a property of `Row`, so the decode ignores it.// This prints `ada unranked`.var $row = Core\Json::decodeAs<Row>("{\"name\":\"ada\",\"rank\":null,\"is_live\":true,\"extra\":1}");echo $row->name, ' ', $row->rank ?? 'unranked', "\n";
// This document has three bad fields, and the error lists all three.try { Core\Json::decodeAs<Row>("{\"rank\":\"first\",\"is_live\":null}");} catch (ParseError $bad) { foreach ($bad->issues as { path: string, message: string } $issue) { echo $issue->path, ': ', $issue->message, "\n"; }}ada unrankedname: required field missingrank: expected int, found a stringis_live: null is not permittedA property needs a constructor parameter
<?nvs// Shows that every property needs a constructor parameter with the same name.// The constructor has no `$name` parameter, so this program does not compile.// proof: compile-error
#[Core\Json\Derive]class User{ public string $name; public int $age;
public function constructor(int $age) { $this->name = ''; $this->age = $age; }}error[E0460]: `$name` has no constructor parameter, so `#[Json\Derive]` cannot decode it --> 05-a-property-needs-a-constructor-parameter.nvs:9:19 |9 | public string $name; | ^^^^^ nothing decodes into this = help: the decoder builds the object with `new`, so every property needs a constructor parameter with the same name. Add one, or write `#[Json\Field(skip: true)]`
error: aborting due to 1 errorTo read what a code means and how to fix it, run `nvs agent show <code>`.Decode an enum and an array
<?nvs// Shows a decode of an enum property and an array property. An enum case is// written in JSON as its number.
enum Level { Low, High }
#[Core\Json\Derive]class Alert{ public Level $level; public array<string> $tags;
public function constructor(Level $level, array<string> $tags) { $this->level = $level; $this->tags = $tags; }}
// `Level::High` is the number 1. This prints {"level":1,"tags":["disk","full"]}.echo Core\Json::encode(new Alert(Level::High, ['disk', 'full'])), "\n";
// This prints `true full`.var $alert = Core\Json::decodeAs<Alert>("{\"level\":1,\"tags\":[\"disk\",\"full\"]}");echo $alert->level == Level::High ? 'true' : 'false', ' ', $alert->tags[1], "\n";
// 7 is not a case of `Level`, and the second tag is not a string.// The path of an array element ends with its index, as `tags.1`.try { Core\Json::decodeAs<Alert>("{\"level\":7,\"tags\":[\"disk\",2]}");} catch (ParseError $bad) { foreach ($bad->issues as { path: string, message: string } $issue) { echo $issue->path, ': ', $issue->message, "\n"; }}{"level":1,"tags":["disk","full"]}true fulllevel: expected a declared enum case, found a numbertags.1: expected string, found a numberKeep the json key order
<?nvs// Shows a class whose `type` key must stay the first key in its JSON.
// `#[Core\Json\KeepKeyOrder]` says that the order of the keys matters.// `nvs code order` then keeps these properties in the order they are written.#[Core\Json\Derive]#[Core\Json\KeepKeyOrder(reason: 'the client reads the type key first')]class Message{ public string $type; public string $text; private int $sentAt;
public function constructor(string $type, string $text, int $sentAt) { $this->type = $type; $this->text = $text; $this->sentAt = $sentAt; }}
// The keys are in the order the properties are written.// This prints {"type":"chat","text":"hello","sentAt":1700}.echo Core\Json::encode(new Message('chat', 'hello', 1700)), "\n";{"type":"chat","text":"hello","sentAt":1700}A subclass writes its parents keys first
<?nvs// Shows a subclass with a JSON codec, which writes its parent's properties first and then its own.
use Core\Json;use Core\Json\Field;
// The parent class does not need `#[Core\Json\Derive]`.// Its `#[Field]` still renames the key in every subclass.class Entity{ #[Field(name: 'id')] public int $key;
public function constructor(int $key) { $this->key = $key; }}
#[Core\Json\Derive]class Post extends Entity{ public string $title;
// The constructor has a parameter for each property, including the inherited one. public function constructor(int $key, string $title) { $this->title = $title; parent::constructor($key); }}
// The key of `Entity` comes first. This prints {"id":7,"title":"hello"}.var $post = new Post(7, 'hello');echo Json::encode($post), "\n";
// A decode calls the constructor of `Post`. This prints `7 hello`.var $back = Json::decodeAs<Post>("{\"id\":7,\"title\":\"hello\"}");echo $back->key, ' ', $back->title, "\n";{"id":7,"title":"hello"}7 helloA property with a set of allowed values
<?nvs// Shows a property that accepts only a fixed set of values, and what a decode does with a value outside it.
use Core\Json;
#[Core\Json\Derive]class Post{ // `$state` is "draft" or "live". `$level` is 1, 2 or 3. public function constructor(public "draft"|"live" $state, public 1|2|3 $level) {}}
// Each value is written as a plain string or number.// This prints {"state":"live","level":2}.echo Json::encode(new Post('live', 2)), "\n";
// This prints `draft 1`.var $post = Json::decodeAs<Post>("{\"state\":\"draft\",\"level\":1}");echo $post->state, ' ', $post->level, "\n";
// "gone" and 7 are not in their sets, so the decode throws a `ParseError`.// It has one issue for each property, with the allowed values.try { Json::decodeAs<Post>("{\"state\":\"gone\",\"level\":7}");} catch (ParseError $bad) { foreach ($bad->issues as { path: string, message: string } $issue) { echo $issue->path, ': ', $issue->message, "\n"; }}{"state":"live","level":2}draft 1state: a `string` of 4 bytes is not one of `"draft"`, `"live"`level: `7` is not one of `1`, `2`, `3`A property that holds any json value
<?nvs// Shows a `mixed` property, which accepts any JSON value, `null` included.
use Core\Json;
#[Core\Json\Derive]class Event{ public function constructor(public string $kind, public mixed $data) {}}
// Each document has a different JSON value under "data".// An encode of the decoded object writes each value back unchanged.array<string> $documents = [ "{\"kind\":\"login\",\"data\":{\"user\":\"ana\",\"roles\":[\"admin\"]}}", "{\"kind\":\"scores\",\"data\":[1,2.5,true]}", "{\"kind\":\"count\",\"data\":42}", "{\"kind\":\"note\",\"data\":\"hello\"}", "{\"kind\":\"empty\",\"data\":null}",];foreach ($documents as string $document) { echo Json::encode(Json::decodeAs<Event>($document)), "\n";}
// `Json::encode` also works on the property alone.// This prints {"user":"ana","roles":["admin"]}.var $login = Json::decodeAs<Event>($documents[0]);echo Json::encode($login->data), "\n";{"kind":"login","data":{"user":"ana","roles":["admin"]}}{"kind":"scores","data":[1,2.5,true]}{"kind":"count","data":42}{"kind":"note","data":"hello"}{"kind":"empty","data":null}{"user":"ana","roles":["admin"]}Dates durations zones and ids as text
<?nvs// Shows how dates, times, durations, time zones and ids are written to JSON as strings.
use Core\Json;use Core\Time\Date;use Core\Time\DateTime;use Core\Time\Duration;use Core\Time\TimeOfDay;use Core\Time\Zone;use Core\Uuid;
#[Core\Json\Derive]class Meeting{ public function constructor( public Uuid $id, public Date $day, public TimeOfDay $opens, public DateTime $starts, public Duration $length, public Zone $zone, ) {}}
var $meeting = new Meeting( Uuid::parse('0190f3a2-7b1c-7def-8a12-3456789abcde'), Date::fromIso('2026-03-02'), TimeOfDay::fromIso('09:00'), DateTime::fromIso('2026-03-02T09:00:00+01:00[Europe/Vienna]'), Duration::parse('1h30m'), Zone::of('Europe/Vienna'),);
// Each property is one JSON string.// The duration is written as `1h30m` and the zone as its name.string $json = Json::encode($meeting);echo $json, "\n";
// A decode reads the same strings back into the classes.// This prints `2026-03-02 5400`.var $back = Json::decodeAs<Meeting>($json);echo $back->day->toIso(), ' ', $back->length->toSeconds(), "\n";
// A string that is not a valid date throws a `ParseError`.// The error names the field.try { Json::decodeAs<Meeting>(Core\Str::replace($json, "\"2026-03-02\"", "\"02.03.2026\""));} catch (ParseError $bad) { echo $bad->issues['0']->path, ': ', $bad->issues['0']->message, "\n";}{"id":"0190f3a2-7b1c-7def-8a12-3456789abcde","day":"2026-03-02","opens":"09:00:00","starts":"2026-03-02T09:00:00+01:00[Europe/Vienna]","length":"1h30m","zone":"Europe/Vienna"}2026-03-02 5400day: expected a date as a string such as 2026-01-05, found a stringDetails
The document has one key for each instance property of the class. A private or protected property has a key too. A property promoted in the constructor has its key in the place where it is written. A static property has no key. A readonly property has a key. A class with no such property is E0758.
A subclass also has a key for each property of its parent classes. The keys of the top parent come first, then the keys of each class below it, and the subclass's own keys come last. A parent does not need #[Core\Json\Derive]. A #[Core\Json\Field] on a parent's property renames or skips that key in every subclass. The subclass's constructor needs a parameter for each inherited key, as for its own properties. If one is missing, the error is reported at the subclass's attribute. A property that a subclass declares again is one key, at the parent's position. A parent from Core gives no keys.
A property may be a number, a string, a bool, mixed, an enum or a set of allowed values. It may also be an inline shape, an array<T> of these, or ?T of these. Another class with #[Core\Json\Derive] is allowed too. A class without the attribute is E0756. An enum case is written in JSON as its number. A float is written with a fraction, so 2 in a float property encodes as 2.0.
A mixed property takes any JSON value: an object, an array, a string, a number, a bool or null. An encode writes the value back as it is.
A set of allowed values is a type such as "draft"|"live" or 1|2|3. All values are strings, or all are numbers. It is written in JSON as the plain string or number. A decode checks that the value is in the set. "gone" gives the issue ` "gone" is not one of "draft", "live" . A long value is cut to 64 characters in the message. ?"pinned" and "a"|"b"|null also accept null`.
Any other type with | is E0756. Examples are string|int, a mix of string and number values, and two classes. Use mixed for a value that can have more than one type.
A secret property is decoded like any other property. Encoding its class does not compile, and is E0462. A lateinit property is E0463. #[Core\Json\Field(skip: true)] leaves either one out. A property with no constructor parameter of the same name is E0460. A parameter of another type is E0461. #[Core\Json\Field] has the options name and skip only, and any other option is E0464. skip: false is the same as no skip.
A constructor parameter that does not match a property in the document is E0820 at the Core\Json::decodeAs call. This is true even when the parameter has a default value. Core\Json::decodeAs on a class without the attribute does not compile, and is E0821. Core\Json::encode of such an object throws a LogicError when it runs.
A ?T property that is null is written as null. It is never left out of the document. A ?T property is always required in a decode too. A missing key is the issue required field missing, as for any other property. Only its value may be null.
A key in the document that the class does not have is ignored.
#[Core\Json\KeepKeyOrder(reason: '...')] on the class says that somebody reads the keys in their order. An example is a client that reads the type key first. The encoder does not change: it always writes the keys in the order the properties are written. The attribute changes what nvs code order and the editor's Order class members action do. They keep the instance properties of this class in their written order. reason is required, and says who needs the order. The attribute on a class without #[Core\Json\Derive] is E0892. Without reason, it is E0401.
The ParseError has every problem in its issues. Each issue has a path and a message.
A decode checks each value's type and does not convert it. 1.5 and 2.0 in an int property are issues, and so is -1 in a uint property. A number in a string or bool property is an issue, and so is a string in a float property. An int in a float property is accepted. An enum property takes the number of a case. Any other number, or a string, is the issue expected a declared enum case.
The path of an issue joins the keys with .. A field of a nested object is address.city, and an array element ends with its index, as tags.1. Core\Json::decodeAs<array<User>> decodes a list, and its paths start with the index, as 1.address.city.
Text that is not valid JSON gives one issue with an empty path. Its message names the line and the column. A document that is a number, a string or null also gives one issue with an empty path. Its message says that the class decodes from a JSON object.
The decode calls your constructor after the checks pass. An error the constructor throws reaches your code unchanged.
Do and don’t
Section titled “Do and don’t”- Do write a constructor that takes every property, with the same names and types.
- Do include the properties of the parent classes in that constructor. The JSON writes them first.
- Do use a set of allowed values, such as
"draft"|"live", for a property with a few fixed values. - Do catch
ParseErrorarounddecodeAswhen the text comes from a user. - Do use
#[Core\Json\Field(skip: true)]for a value that is only a cache. - Do declare a password that a request sends as
secret tainted string. The decoder fills it, and encoding the class does not compile. - Do add
#[Core\Json\KeepKeyOrder(reason: '...')]when another program reads the keys in their order.nvs code orderthen keeps the properties of the class in the order you wrote them.
