Metano transpiles System.Text.Json.Serialization.JsonSerializerContext
subclasses into a TypeScript SerializerContext with pre-computed TypeSpec
definitions. JSON property names, naming policies, and per-property overrides
are all resolved at compile time — no runtime reflection, no string
comparisons.
There are three representations of your data, and each transition has its own rules:
flowchart TD
CS[C# source]
TS[TypeScript target]
JSON[JSON wire format]
CS -->|transpile| TS
TS -->|stringify| JSON
JSON -->|parse| TS
Naming conventions differ at each layer:
| Layer | Default naming | Example |
|---|---|---|
| C# property | PascalCase | FirstName |
| JSON wire | depends on JsonSourceGenerationOptions (PropertyNamingPolicy, or camelCase under JsonSerializerDefaults.Web) |
firstName, first_name, FirstName |
| TypeScript field | camelCase (Metano convention) | firstName |
The TypeScript toJSON() and fromJSON() maps TS field ↔ JSON wire — C#
is the source of truth for deriving both, but they don't know about each other.
Input — JsonContext.cs:
using System.Text.Json.Serialization;
using Metano.Annotations;
namespace TestApp;
[Transpile]
[StringEnum]
public enum Priority
{
Low,
Medium,
High,
}
[Transpile]
public record TodoItem(string Title, bool Completed, Priority Priority);
[Transpile]
[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.SnakeCaseLower)]
[JsonSerializable(typeof(TodoItem))]
public partial class JsonContext : JsonSerializerContext;Every type the context describes must be transpiled ([Transpile], or
[assembly: TranspileAssembly] as in the rest of this page's examples): a root
that is not is error MS0035 ('TestApp.TodoItem' cannot be a [JsonSerializable] root: it is not a transpiled class or struct of this project or of a referenced Metano package, so it has no TypeScript contract.).
Output — json-context.ts:
import { SerializerContext, type TypeSpec } from "metano-runtime/system/json";
import { Priority } from "./priority";
import { TodoItem } from "./todo-item";
export class JsonContext extends SerializerContext {
private static readonly _default: JsonContext = new JsonContext();
private _todoItem?: TypeSpec<TodoItem>;
static get default(): JsonContext {
return this._default;
}
get todoItem(): TypeSpec<TodoItem> {
return this._todoItem ??= this.createSpec({
type: TodoItem,
factory: (p: Record<string, unknown>) => new TodoItem(p.title as string, p.completed as boolean, p.priority as Priority),
properties: [
{ ts: "title", json: "title", type: { kind: "primitive" } },
{ ts: "completed", json: "completed", type: { kind: "primitive" } },
{ ts: "priority", json: "priority", type: { kind: "enum", values: Priority } },
],
});
}
}(The printer writes each property object on several lines; they are folded here and in the other snippets of this page.)
Usage from TS:
import { JsonSerializer } from "metano-runtime/system/json";
import { JsonContext } from "./json-context";
import { Priority } from "./priority";
import { TodoItem } from "./todo-item";
const todo = new TodoItem("Write docs", false, Priority.High);
// TS → JSON
const wire = JsonSerializer.serialize(todo, JsonContext.default.todoItem);
// → { title: "Write docs", completed: false, priority: "High" }
// JSON → TS (TodoItem | null: JSON `null` reads as `null`, as in STJ)
const parsed = JsonSerializer.deserialize(wire, JsonContext.default.todoItem);
// → TodoItem { title: "Write docs", completed: false, priority: "High" }
// JSON text → TS, as STJ's Deserialize(string): decimals keep every digit
const fromText = JsonSerializer.deserializeText(
JSON.stringify(wire),
JsonContext.default.todoItem,
);deserialize takes the tree JSON.parse built; deserializeText takes the
JSON text, reads each decimal from its exact digits and throws .NET's
JsonException messages for invalid text (details). Both
return TodoItem | null (Null roots).
C# code that serializes through the context transpiles to the same runtime API.
Context.Default reads the emitted static get default(), and the static
System.Text.Json calls over a JsonTypeInfo are mapped:
var json = JsonSerializer.Serialize(todo, JsonContext.Default.TodoItem);
var back = JsonSerializer.Deserialize(json, JsonContext.Default.TodoItem);const json = JsonSerializer.serializeText(todo, JsonContext.default.todoItem);
const back = JsonSerializer.deserializeText(json, JsonContext.default.todoItem);| C# | TypeScript | Behavior (as measured on .NET 10) |
|---|---|---|
JsonSerializer.Serialize(value, JsonTypeInfo<T>), Serialize(object?, JsonTypeInfo) |
JsonSerializer.serializeText(value, spec) |
JSON text as STJ's default options write it: no whitespace; strings escaped by the default encoder (" is \u0022, < is \u003C, every non-ASCII code unit is \uXXXX, a lone surrogate is \uFFFD); numbers in .NET's round-trip text (1E+20, 1E-07, -0); decimal and 64-bit integers with their exact digits; a null root as null. NaN and the infinities throw ArgumentException. |
JsonSerializer.Deserialize(string, JsonTypeInfo<T>), Deserialize(string, JsonTypeInfo) |
JsonSerializer.deserializeText(text, spec) |
Exact reads; invalid text throws JsonException; the text null reads as null (Null roots). |
A null text or type info throws ArgumentNullException (parameter json /
jsonTypeInfo), as .NET does. The overloads that take JsonSerializerOptions,
a Type, a stream, a Utf8JsonWriter, a span or a JsonElement stay unmapped
(MS0001). serializeText writes the text layout of the context's
[JsonSourceGenerationOptions]: compact by default, and with WriteIndented = true
each element and property on its own line, IndentCharacter (a space or a tab) repeated
IndentSize times per level (2 spaces by default), NewLine between lines ("\n" or
"\r\n"), ": " after a property name and [] / {} for an empty container, as
.NET 10 writes them. An unset NewLine writes "\n", the .NET default on Linux and macOS
(it is Environment.NewLine, so "\r\n" on Windows). The options travel with the spec
the context creates, as ctx.T.Options does in .NET; the tree serialize returns is not
text and is unaffected. A value System.Text.Json rejects (an indent character other than a
space or a tab, a size above 127, another NewLine) warns MS0037. Options passed to the
context's constructor at runtime are invisible, as for every other option.
Behavior change since 3.1.0. In 3.1.0
serializeTextalways wrote compact text. A context withWriteIndented = truenow produces indented text; call sites that relied on the compact text of such a context must setWriteIndented = false(as .NET itself would).
When it sees a class that inherits from JsonSerializerContext:
-
Reads
[JsonSourceGenerationOptions]— resolves the naming policy (CamelCase,SnakeCaseLower,SnakeCaseUpper,KebabCaseLower,KebabCaseUpper, ornull/default for PascalCase preservation). TheJsonSerializerDefaults.Webconstructor argument selectsCamelCase, and a namedPropertyNamingPolicyoverrides it (see Web defaults). -
Collects
[JsonSerializable(typeof(T))]attributes — eachTbecomes a lazy getter on the context class (see Roots for the accepted types, the getter names and the diagnostics). -
Adds every object type reachable from those roots, as System.Text.Json does: types reached through property types, array / list / set elements, dictionary keys and values, nullable underlying types, and base types each get their own getter, so every
refdescriptor andbaselink resolves. Roots come first, in declaration order, followed by the discovered types in breadth-first order; each type is emitted once, and cycles (A → B → A) terminate. The element, dictionary value and nullable inner types of a collection root are discovered the same way, sotypeof(ShotTiming[])also emitsshotTiming. Classes and structs are discovered when they are transpiled in their declaring assembly: this project (nested ones included) or a referenced[TranspileAssembly]+[EmitPackage]library, whose types the context imports from the package (and adds topackage.json#dependencies). Closed generic types are discovered under their constructed name (Page<EpisodeSummary>→pageEpisodeSummary, withTypeSpec<Page<EpisodeSummary>>). Interfaces are not discovered. Base types, including a base declared in a referenced library, are included whenever the spec links to them throughbase. Every type registered with[JsonDerivedType]by a polymorphic base the context dispatches through (a root, a property / element / value type, or a registered type) is added too, in attribute order, with its own base chain and property types, even when no root names it (see Polymorphism). -
For each serializable type
T, walks the members System.Text.Json's source generator serializes (see Member selection) and:- Excludes
[JsonIgnore](unlessCondition = Never),[JsonExtensionData]and static members - Resolves the JSON name:
[JsonPropertyName]override wins, otherwise applies the context's naming policy to the C# member name - Classifies the member type (primitive, temporal, decimal, bytes, array, map, branded, enum, ref, etc.)
- Records a non-zero
[JsonPropertyOrder]as the property'sorder
- Excludes
-
Emits a
TypeSpec<T>as a lazy getter on theSerializerContextsubclass, with pre-computedts/jsonnames, for every object type, and aValueSpec<T>for every other root.
Metano versions the transpiler tools and metano-runtime together, and a
generated context needs the runtime of the same major version. A context
generated by Metano 3.0 uses runtime members that earlier runtimes lack
(polymorphism descriptors with abstract entries and baseTest, readOptions,
valueType, the bytes descriptor, PropertySpec.order, assignIfPresent,
deserializeText), so it needs metano-runtime 3.0.0 or later. For
reference, value roots (ValueSpec) first shipped in 2.8.0 and the runtime's
polymorphic dispatch in 2.10.0; [JsonFactory] needs no runtime change.
You rarely set this by hand: every generated package that imports
metano-runtime declares it as a peerDependency of ^<transpiler version>,
unless your package.json already declares it. The 3.0 release is a major
version because of the breaking changes in Migrating to 3.0.
[JsonSerializable] accepts the same root types as System.Text.Json:
| Root | Getter | Spec |
|---|---|---|
typeof(EpisodeSummary) (a transpiled class, record or struct) |
episodeSummary |
TypeSpec<EpisodeSummary> |
typeof(IReadOnlyList<EpisodeSummary>) |
iReadOnlyListEpisodeSummary |
ValueSpec<EpisodeSummary[] | null> |
typeof(EpisodeSummary[]) |
episodeSummaryArray |
ValueSpec<EpisodeSummary[] | null> |
typeof(IEnumerable<Leaf>) |
iEnumerableLeaf |
ValueSpec<Iterable<Leaf> | null> |
typeof(Dictionary<string, EpisodeSummary>) |
dictionaryStringEpisodeSummary |
ValueSpec<Map<string, EpisodeSummary> | null> |
typeof(HashSet<string>) |
hashSetString |
ValueSpec<HashSet<string> | null> |
typeof(string), typeof(int), typeof(int?) |
string, int32, nullableInt32 |
ValueSpec<string | null>, ValueSpec<number>, ValueSpec<number | null> |
typeof(Guid), a [StringEnum], a [Branded] type |
guid, the type's name |
ValueSpec<UUID>, ValueSpec<Mood>, ValueSpec<EpisodeId> |
typeof(List<string>), TypeInfoPropertyName = "Names" |
names |
ValueSpec<string[] | null> |
A ValueSpec holds the same descriptor the type gets as a property, so it goes
through the same converters (custom converters still match by kind):
const json = JsonSerializer.serialize(shots, AppJsonContext.default.shotTimingArray);
const restored = JsonSerializer.deserialize(data, AppJsonContext.default.shotTimingArray); // ShotTiming[] | nullA reference-type root (a collection, dictionary, set or string) is typed
T | null, because JSON null reads back as null; a value-type root is not,
and carries valueType: true instead (Null roots).
IEnumerable<T> / IReadOnlyCollection<T> roots and properties serialize any
iterable (a Set, a generator, a LINQ pipe) as a JSON array.
Names follow System.Text.Json's JsonTypeInfo property names, camel-cased:
a non-generic type uses its TypeScript name (so [Name] applies); a closed
generic type is its name without arity followed by its type arguments' names
(ListListInt32); an array is its element's name + Array; Nullable<T> is
Nullable + T's name; BCL types use their CLR names (String, Int32,
Guid, DateTimeOffset). TypeInfoPropertyName replaces the name of its type
everywhere in the context, including ref / base links and the names of
generic types that use it as an argument. Type arguments use the same rule, so
[Name("User")] UserDto makes List<UserDto> → listUser (System.Text.Json:
ListUserDto).
Diagnostics:
MS0035(error) rejects a root the context cannot describe: an open generic,object, a non-collection interface without[JsonDerivedType]registrations, a type that is not a transpiled class or struct (KeyValuePair<,>, tuples,[Ignore]/[External]types, types of non-Metano assemblies, and the dictionary types that are not recognized as dictionaries yet:SortedDictionary,ReadOnlyDictionary,FrozenDictionary), an array of rank > 1, a dictionary with non-stringkeys (not supported yet), a collection whose element type has no spec in the context (an interface or a type that is not transpiled), or a closed generic whose type argument has no spec (Page<System.Version>).MS0001(error) rejects a serialized member whose type has no spec in the context for the same reasons (object,KeyValuePair<,>, tuples, types of non-Metano assemblies), anywhere in its descriptor (List<KeyValuePair<string, int>>); leave it out with[JsonIgnore](#713). A member typed as a non-polymorphic interface is not rejected: it claims a write-only spec (#502).MS0072(error) reports two properties of a contract that map to the same JSON name, which System.Text.Json rejects on first use (#442).MS0036reports two types that map to one getter (a warning that drops an unreferenced root, an error when the losing type is referenced by another spec), a getter that would shadow aSerializerContextmember (options,converters,createSpec,createValueSpec,readOptions,writeOptions,resolve,_registry,constructor), and a type listed twice with differentTypeInfoPropertyNamevalues (a warning; the first one is kept). UseTypeInfoPropertyNameto resolve a collision.
Divergences: Stack<T> is written and read in array order (System.Text.Json
writes it top-first and reverses it on read); the [Name] naming above.
Getter renames (#270): every getter now comes from the naming rule above.
A type whose camel-cased name is a JavaScript reserved word keeps the bare
name, because getters sit in property position: Delete → get delete()
(previously get delete_()), Default → get default() (previously
default_; it does not clash with the static JsonContext.default). Update
call sites such as ctx.delete_ to ctx.delete.
JSON null at a root reads and writes as System.Text.Json does (measured on
.NET 10 with a source-generated context):
| Root | deserialize(null, …) / deserializeText("null", …) |
Return type |
|---|---|---|
A class or record contract, polymorphic and interface bases, a [PlainObject] type |
null |
T | null (TypeSpec<T>) |
A collection, dictionary, set, string, byte[] |
null |
T | null (ValueSpec<T | null>) |
Nullable<T> (int?, SPoint?) |
null |
T | null (ValueSpec<T | null>) |
A struct / record struct contract |
throws The JSON value could not be converted to MyApp.SPoint. |
T | null (TypeSpec<T>; the throw makes the null impossible) |
Another value type (int, bool, Guid, decimal, an enum, a branded type, a temporal type) |
throws The JSON value could not be converted to <Type>. |
T (ValueSpec<T>) |
- The generator marks every C# value type except
Nullable<T>withvalueType: trueand its CLRtypeName, as .NET prints it (System.Int32,MyApp.Level,MyApp.Outer+Inner,MyApp.Pair`1[System.Int32]): on the struct contract'sTypeSpec(wherever the closure reaches it) and on a value root'sValueSpec. The message names thattypeName; a hand-written spec without one names its constructor, orObjectfor a value spec. - At the root the check runs before any converter, custom ones included.
Below the root, JSON
nullfor a struct contract throws the same error for a property ({"P":null}forrecord Holder(SPoint P)), a list or set element and a dictionary value, as in .NET;SPoint?still readsnull. serialize(value, spec)through aTypeSpecreturns the written object for a non-nullvalue, andnullfornull. A struct contract shares that overload, soserialize(null, structSpec)also returnsnull, a value C# cannot express (a struct is nevernull). A value root convertsnullthrough its descriptor, which writesnull.- Not mirrored: a value-type custom converter. .NET passes the
nulltoken to a custom converter of a value type, which decides what it reads; Metano throws before any converter runs (the null checks of a property, an element and a dictionary value precede the custom converter lookup, #512). JSONnullfor anint,bool, enum, branded, temporal ordecimalproperty, element or dictionary value throws as .NET does (#471): a property names its declaring contract (MyApp.Holder, a[PlainObject]contract its CLR name, #512), an element or a dictionary value its own type (System.Int32). - An empty or blank text has no JSON token:
deserializeText("", …)throwsThe input does not contain any JSON tokens. Expected the input to start with a valid JSON token, when isFinalBlock is true.for every root, as STJ does.
The runtime (metano-runtime/system/json) interprets TypeSpec objects and
handles these kinds:
| Kind | TS type | On serialize | On deserialize |
|---|---|---|---|
primitive |
string, number, boolean | passthrough | passthrough; a JSON string for a numeric numberType when the context reads numbers from strings (details) |
temporal |
Temporal.PlainDate, etc. |
.toString() |
Type.from(iso) |
decimal |
Decimal |
JSON.rawJSON(value.toFixed()): its exact digits as a JSON number (details) |
new Decimal(…) from the JSON number (its exact digits through deserializeText), or from the JSON string when the context reads numbers from strings, rounded as .NET rounds it; anything else, or a value outside the decimal range, throws The JSON value could not be converted to System.Decimal. |
bytes |
number[] (C# byte[]) |
padded standard base64, one line ([1,2,3] → "AQID") |
base64 as System.Text.Json reads it: space, tab, CR and LF ignored; anything else invalid throws The JSON value could not be converted to System.Byte[]. |
array |
T[] / Iterable<T> |
Array.from(iterable, serialize) |
.map(deserialize) |
map |
Map<K,V> |
Object.fromEntries(...), each key written as text (below) |
new Map(Object.entries(...)), each property name parsed into the key type (below) |
hashSet |
HashSet<T> |
Array.from(set, serialize) |
new HashSet(arr) |
branded |
[Branded] / [InlineWrapper] type |
passthrough (brand erases at runtime) | Type.create(value), or the type's [JsonFactory] (below) |
enum |
string enum | passthrough (already string) | validates against allowed values |
numericEnum |
numeric enum | passthrough | any integer of the underlying type (numberType, int when absent), member or not, as System.Text.Json reads it (#369) |
nullable |
T | null |
null passes through, else recurse |
same |
ref |
another spec | recursive serialize with target spec |
recursive deserialize |
A JSON property name is always a string, so the key descriptor of a dictionary carries what the runtime needs to read it back into the key's C# type, the way System.Text.Json does (measured on .NET 10), whatever the context's read options (#479):
| Key type | Key descriptor | Written | Read |
|---|---|---|---|
string |
{ kind: "primitive" } |
as is | as is |
int, long, short, byte, uint, … |
{ kind: "primitive", numberType: "System.Int32" } |
String(n) |
the numbers-from-strings grammar: "+5", "007" and "-0" read for a signed type, digits only for an unsigned one; whitespace, "1.0", "1e2", "" and out-of-range values throw |
float, double |
numberType: "System.Single" / "System.Double" |
String(n) |
the same grammar, "NaN" and "Infinity" included |
bool |
{ kind: "primitive", typeName: "System.Boolean" } |
True / False |
true / false in any case, no whitespace |
| numeric enum | { kind: "numericEnum", values: Level, numberType: "System.Int32", typeName: "MyApp.Level" } (numberType is the underlying type) |
the member name (High; an aliased value by its first member), or the number when no member has it |
a member name in any case, a comma-separated list of names (OR-ed), or an integer with an optional sign, any value in the underlying type's range, member or not; surrounding whitespace ignored |
[StringEnum] |
{ kind: "enum", values: Mood, typeName: "MyApp.Mood" } |
the value | a member value in any case; surrounding whitespace ignored |
Guid |
{ kind: "branded", create: UUID.create, typeName: "System.Guid" } |
as is | the D format (8-4-4-4-12) in any case, read as lowercase; braces, the N format and whitespace throw |
decimal |
{ kind: "decimal", type: Decimal } |
toFixed() |
the decimal grammar (Decimals) |
DateOnly and the other temporal types |
{ kind: "temporal", parse: …, typeName: "System.DateOnly" } |
as its value is written | the descriptor's parse |
a [Branded] type |
{ kind: "branded", create: … } |
as is | create(name), unchanged |
A property name the key type rejects throws JsonException The JSON value could not be converted to System.Int32. (the key's CLR name: System.Guid,
MyApp.Level), on the tree and the text paths alike. Two names that read as
the same key ("1" and "01") keep the value of the one JS enumerates last,
which puts integer-like names first: {"01":1,"1":2} reads 1 (.NET keeps
the last in the text, 2). A custom converter of the key's kind still takes
precedence.
A long / ulong key reads as a number while 64-bit integers are numbers
(spec 012 turns them into bigint; 64-bit numbers). A
dictionary with a non-string key can be a property but not yet a
[JsonSerializable] root (MS0035, Roots).
A [Branded] type's descriptor calls Type.create(value), which only casts: the validation you
wrote in C# (From) never runs on JSON input. Mark the validating method with [JsonFactory] and
the descriptor calls it instead:
From the conformance sample (samples/SampleJsonContracts/Title.cs):
[Branded]
public readonly record struct Title(string Value)
{
[JsonFactory]
public static Title From(string value)
{
var trimmed = value.Trim();
if (trimmed.Length == 0)
{
throw new ArgumentException("blank");
}
return new Title(trimmed);
}
}
public sealed record EpisodeRec(string Id, Title Note);get title(): ValueSpec<Title> {
return (this._title ??= this.createValueSpec({
descriptor: { kind: "branded", create: Title.from }, // without [JsonFactory]: Title.create
valueType: true,
typeName: "SampleJsonContracts.Title",
}));
}
// in the spec of EpisodeRec
{ ts: "note", json: "Note", type: { kind: "branded", create: Title.from } },JsonSerializer.deserialize then throws the factory's own error for " " (the transpiled
Title.from throws Error("blank")) and returns "ok" for " ok ". Exceptions propagate unchanged, at any nesting depth (nullable, array, map value and map
key positions, and branded value roots). The member name is the one the companion declares, so
[Name("parse")] gives create: Title.parse, and a nested type gives create: Episode.Code.from.
A valid factory is a named static method (any accessibility) with exactly one parameter of the
wrapper's underlying type, returning the containing type; it is neither generic nor overloaded, is
emitted for TypeScript, is the type's only [JsonFactory], and its TypeScript name is not create
or toString nor used by another method of the type. Anything else, or [JsonFactory] on a non-branded type, is error MS0034 and the
descriptor keeps create. Without the attribute nothing changes.
In a library that declares [EmitPackage] the factory must be public: consumers compile against
the library's metadata, which omits non-public members, so a private factory would be dropped
there without notice and is reported as MS0034 instead. Changing a library's factory without a
version bump can leave a consumer's cached context stale (the per-group cache does not track
referenced packages).
This is TypeScript-only: Metano ships no System.Text.Json converter that calls the factory, so
on the C# side System.Text.Json still writes the record struct as an object unless you supply
your own JsonConverter.
| C# attribute | Handled by Metano? | Effect |
|---|---|---|
[JsonSerializable(typeof(T))] |
✅ | Adds T and every object type reachable from it to the context's type list; collection, dictionary, set, primitive, enum, branded and nullable roots get a ValueSpec |
[JsonSerializable(..., TypeInfoPropertyName = "X")] |
✅ | Names the getter x for that type everywhere in the context |
[JsonFactory] (Metano) |
✅ | On a [Branded] type's static method: deserialization calls it instead of create (details) |
[JsonSourceGenerationOptions] with PropertyNamingPolicy |
✅ | Applies the naming policy to all properties |
[JsonSourceGenerationOptions(JsonSerializerDefaults.Web)] |
✅ | camelCase names, case-insensitive property names and numbers read from strings, as in .NET (details) |
[JsonSourceGenerationOptions] with PropertyNameCaseInsensitive, NumberHandling = AllowReadingFromString or AllowOutOfOrderMetadataProperties |
✅ | Mirrored in the context's readOptions (details); the other NumberHandling flags (WriteAsString, AllowNamedFloatingPointLiterals) are not |
[JsonPropertyName("wire_name")] |
✅ | Overrides the wire name for that property |
[JsonIgnore] |
✅ | Excludes the property from the spec; on an override, also hides the base declarations (details). Condition = Never keeps it; WhenWritingNull (and WhenWritingDefault on a nullable member) keeps it and leaves it out of the written JSON when it is null (omitWhenNull); WhenWritingDefault on a non-nullable member, WhenWriting and WhenReading keep it too, always written and read, and warn MS0037 |
[JsonInclude] |
✅ | Serializes a field or an internal / protected internal property (details); on a member the source generator cannot reach, warns MS0037 |
[JsonPropertyOrder(n)] |
✅ | Emitted as the property's order; the runtime sorts the whole hierarchy by it (details) |
JsonKnownNamingPolicy.CamelCase |
✅ | FirstName → firstName |
JsonKnownNamingPolicy.SnakeCaseLower |
✅ | FirstName → first_name |
JsonKnownNamingPolicy.SnakeCaseUpper |
✅ | FirstName → FIRST_NAME |
JsonKnownNamingPolicy.KebabCaseLower |
✅ | FirstName → first-name |
JsonKnownNamingPolicy.KebabCaseUpper |
✅ | FirstName → FIRST-NAME |
Default (null, JsonKnownNamingPolicy.Unspecified) |
✅ | Preserves PascalCase (FirstName → FirstName) |
[JsonConverter] |
Not mirrored, MS0037 — use custom converters at runtime instead. Not reported on a [Branded] / [InlineWrapper] type, whose descriptor already writes the wrapped value |
|
[JsonRequired], C# required |
✅ / |
A non-nullable member is already required on read; on a nullable member a missing key reads null where STJ throws, MS0037 |
[JsonExtensionData] |
Left out of the spec, MS0037; bound to a constructor parameter (STJ throws InvalidOperationException), the factory passes null |
|
[JsonNumberHandling], [JsonObjectCreationHandling(Populate)], [JsonUnmappedMemberHandling(Disallow)] |
Not mirrored, MS0037 |
|
[JsonConstructor] |
✅ / |
A class with two or more constructors is built through the factory of the marked overload (factory: (p) => Money.fromAmountCurrency(…), spec 013 FR-035). Any other type is built through the constructor the factory calls (the primary one, else the one with the most parameters); the attribute on another constructor (a [PlainObject] secondary one, a type read from a DLL or package) reports MS0037 |
Any other [JsonSourceGenerationOptions] option |
MS0037 when set to a value other than System.Text.Json's default; DefaultBufferSize / GenerationMode are never reported, and the text options (WriteIndented, IndentCharacter, IndentSize, NewLine) are mirrored by serializeText and reported only for a value System.Text.Json rejects (details) |
|
[JsonDerivedType] / [JsonPolymorphic] on a class or record |
✅ | Emits the base's polymorphism descriptor and a spec for every registered type (details) |
[JsonDerivedType] on an interface or a [PlainObject] type |
✅ | Interface bases dispatch class variants by constructor; [PlainObject] variants are selected by synthesized guards (details) |
The context serializes the members System.Text.Json's source generator serializes (measured on .NET 10, spec 009 FR-046, DECIDED-25):
- Public instance properties, as before.
- With
[JsonInclude], a field or a non-public property, when the member and its accessors arepublic,internalorprotected internal. Aprivateorprotected[JsonInclude]member (or a public property with aprivatesetter) makes the System.Text.Json contract throwInvalidOperationException(SYSLIB1038); the transpiler warnsMS0037and leaves a non-public one out. A public field without[JsonInclude]is not serialized (IncludeFieldswarnsMS0037). - Each type lists its properties, then its fields; the FR-009 hierarchy order applies across types (Inheritance).
[JsonPropertyOrder(n)]sorts the properties of the whole hierarchy byn, stably (absent counts as0); the attribute of the most-derived declaration counts, so an override without it has order0:
public class OrdBase
{
public int Base1 { get; set; } = 1;
[JsonPropertyOrder(5)]
public int Base2 { get; set; } = 2;
[JsonPropertyOrder(-5)]
public int Base3 { get; set; } = 3;
}
public class OrdDer : OrdBase
{
public int Der1 { get; set; } = 10;
[JsonPropertyOrder(-5)]
public int Der2 { get; set; } = 20;
[JsonPropertyOrder(1)]
public int Der3 { get; set; } = 30;
}
// new OrdDer() → {"Der2":20,"Base3":3,"Der1":10,"Base1":1,"Der3":30,"Base2":2}get ordDer(): TypeSpec<OrdDer> {
return this._ordDer ??= this.createSpec({
type: OrdDer,
base: this.ordBase,
factory: (p: Record<string, unknown>) => new OrdDer(),
properties: [
{ ts: "der1", json: "Der1", type: { kind: "primitive" } },
{ ts: "der2", json: "Der2", type: { kind: "primitive" }, order: -5 },
{ ts: "der3", json: "Der3", type: { kind: "primitive" }, order: 1 },
],
assignIfPresent: ["base1", "base2", "base3", "der1", "der2", "der3"],
});
}The runtime writes new OrdDer() through this spec as
{"Der2":20,"Base3":3,"Der1":10,"Base1":1,"Der3":30,"Base2":2}, the text .NET
writes.
On read, the factory passes the constructor's parameters. Members no parameter
binds are set as System.Text.Json sets them: an init or required member
always, through Object.assign(new T(…), { … }) (a missing nullable one reads
null; a missing non-nullable one throws, where STJ sets 0 / the default),
and a member with a set accessor or a writable field that the contract's own
constructor does not bind (inherited ones included) only when the payload
carries its key (the spec's assignIfPresent: [...] list; the runtime assigns
it after construction, in wire order where STJ follows the payload's order),
so a missing key keeps the constructed value. One FR-045 difference remains on
both paths: a missing non-nullable key throws in the runtime, where STJ uses the
default (an init value type, 0) or keeps the initializer (a non-nullable
set member of a [PlainObject] type, whose literal has no initializer to keep):
public class Init
{
public string? Note { get; set; } = "init";
public int Count { get; set; } = 5;
}
// {"Count":1} → Note = "init", Count = 1 (STJ and TypeScript alike)
public sealed record InitRec(int A)
{
public string? Note { get; init; }
}get init(): TypeSpec<Init> {
return this._init ??= this.createSpec({
type: Init,
factory: (p: Record<string, unknown>) => new Init(),
properties: [
{ ts: "note", json: "Note", type: { kind: "nullable", inner: { kind: "primitive" } }, optional: true },
{ ts: "count", json: "Count", type: { kind: "primitive" } },
],
assignIfPresent: ["note", "count"],
});
}
get initRec(): TypeSpec<InitRec> {
return this._initRec ??= this.createSpec({
type: InitRec,
factory: (p: Record<string, unknown>) => Object.assign(new InitRec(p.a as number), { note: p.note as string | null }),
properties: [
{ ts: "a", json: "A", type: { kind: "primitive" } },
{ ts: "note", json: "Note", type: { kind: "nullable", inner: { kind: "primitive" } }, optional: true },
],
});
}{} reads as Init { note: "init", count: 5 }; for InitRec it throws
Missing required property: "A".
A get-only property is written and still required on read (see
Errors and limits). A public property with a non-public
getter is not serialized, and an internal [JsonInclude] member of another
assembly is reachable only when that assembly grants the context's
InternalsVisibleTo.
A byte[] is written as base64 ([255,254,253] → "//79") and read back with
System.Text.Json's rules; List<byte> stays a number array. From the
conformance sample (samples/SampleJsonContracts, manifest row M1):
public sealed record Blob(byte[] Data, byte[]? Maybe, List<byte> Numbers);
// new Blob([1, 2, 3], [255, 254], [1, 2]) → {"Data":"AQID","Maybe":"//4=","Numbers":[1,2]}properties: [
{ ts: "data", json: "Data", type: { kind: "bytes" } },
{ ts: "maybe", json: "Maybe", type: { kind: "nullable", inner: { kind: "bytes" } }, optional: true },
{ ts: "numbers", json: "Numbers", type: { kind: "array", element: { kind: "primitive" } } },
],A null byte[]
property, List<byte[]> element or Dictionary<string, byte[]> value is written
null, where a source-generated context's fast path writes "" (which it then
reads back as an empty array).
Everything else System.Text.Json offers is either mirrored or reported with
warning MS0037 (UnmirroredJsonOption) at the option or attribute, so no
option or attribute is ignored silently (the remaining differences are the
documented divergences of spec 009): the unmirrored [JsonSourceGenerationOptions]
options set to a non-default value (DefaultIgnoreCondition other than Never and
WhenWritingNull, which the generated context mirrors; IgnoreReadOnlyProperties, IgnoreReadOnlyFields, IncludeFields,
UseStringEnumConverter, Converters, ReferenceHandler,
DictionaryKeyPolicy, ReadCommentHandling, AllowTrailingCommas,
AllowDuplicateProperties, UnmappedMemberHandling, UnknownTypeHandling,
PreferredObjectCreationHandling, RespectNullableAnnotations,
RespectRequiredConstructorParameters, MaxDepth other than 64, and each
NumberHandling flag but AllowReadingFromString) and the attributes in the
table above. The full list is in
the diagnostics contract.
[JsonSourceGenerationOptions(JsonSerializerDefaults.Web)] sets three options
in .NET: the camelCase naming policy, case-insensitive property names and
numbers read from strings. Metano mirrors all three: names are computed at
transpile time, and the two read options are emitted once on the context.
[JsonSourceGenerationOptions(JsonSerializerDefaults.Web)]
[JsonSerializable(typeof(Clip))]
[JsonSerializable(typeof(Stats))]
public partial class WebJsonContext : JsonSerializerContext;
public sealed record Stats(int Count, double Ratio);export class WebJsonContext extends SerializerContext {
protected override get readOptions(): JsonReadOptions {
return { propertyNameCaseInsensitive: true, numberHandling: "allowReadingFromString" };
}
get stats(): TypeSpec<Stats> {
return this._stats ??= this.createSpec({
type: Stats,
factory: (p: Record<string, unknown>) => new Stats(p.count as number, p.ratio as number),
properties: [
{ ts: "count", json: "count", type: { kind: "primitive", numberType: "System.Int32" } },
{ ts: "ratio", json: "ratio", type: { kind: "primitive", numberType: "System.Double" } },
],
});
}
}- Property names are camel-cased at transpile time by the same rule .NET uses:
URL→url,IOStream→ioStream,ABC_D→abC_D,Item_Name→item_Name; a name that does not start with an uppercase letter (alreadyCamel,_Leading) is kept. - A named
PropertyNamingPolicyoverrides the Web default, as in .NET:(JsonSerializerDefaults.Web, PropertyNamingPolicy = JsonKnownNamingPolicy.SnakeCaseLower)writesfirst_name, andPropertyNamingPolicy = JsonKnownNamingPolicy.Unspecifiedturns the policy off (FirstName). [JsonPropertyName]still wins over any policy.- The discriminator of a polymorphic type is never renamed:
$typeor theTypeDiscriminatorPropertyNameyou set ("Kind"stays"Kind"), and it is matched case-sensitively on read.
Read options. The context overrides readOptions only when an option
differs from .NET's default; createSpec and createValueSpec attach them to
every spec, so JsonSerializer.deserialize(data, ctx.stats) honors them too. A
named option overrides the Web default, as in .NET:
(JsonSerializerDefaults.Web, PropertyNameCaseInsensitive = false) reads names
case-sensitively again, and NumberHandling = JsonNumberHandling.Strict stops
reading numbers from strings. PropertyNameCaseInsensitive = true,
NumberHandling = JsonNumberHandling.AllowReadingFromString and
AllowOutOfOrderMetadataProperties = true are mirrored on their own too.
- Case-insensitive names. JSON keys match property names the way .NET's
OrdinalIgnoreCasedoes (PATHandpAtHreadPath); keys apply in document order, so with two matching keys the last one wins ({"path":"a","Path":"b"}reads"b"). The discriminator stays case-sensitive ({"Kind":"image"}is a missingkindtag) and is never read as a property.ß,ıandſdo not matchSS,IandS, as in .NET; characters whose casing differs between the JS engine's Unicode version and .NET's may compare differently. - Numbers from strings. Numeric properties, collection elements, dictionary
values and roots accept a JSON string by .NET's grammar: signed integers take
an optional sign and leading zeros (
"+5","007","-0"→0); unsigned integers take digits only ("+5"and"-0"are rejected forbyte,ushort,uintandulong);float/doubletake"1e2","1.",".5","+1.5"and the exact"NaN","Infinity","-Infinity";decimaltakes the same text without the named literals. Whitespace, hex,"", digit separators and out-of-range values are rejected withJsonExceptionThe JSON value could not be converted to System.Int32.(the CLR name of the type, orSystem.Nullable`1[System.Int32]forint?). Enums, the text"null"for a nullable number and integer type discriminators never read strings, as in .NET; dictionary keys are always text and read by the same grammar whatever the option (Dictionary keys). Writing is unchanged: numbers are written as JSON numbers. Adecimalread from a string is built from the exact text, so"1.2345678901234567890123456789"keeps its significant digits (trailing zeros are dropped:"1.10"reads as1.1), rounded to 28 decimal places as .NET rounds it ("1e-29"reads as0). - Out-of-order metadata.
AllowOutOfOrderMetadataProperties = truelets the type discriminator follow other properties (details). - Divergences. For a property bound to a constructor parameter (a record's
positional property), .NET names the declaring type in the error (
The JSON value could not be converted to TestApp.Stats.); Metano names the numeric type. Afloatread from a string keeps double precision, as afloatread from a JSON number already does. Two properties whose names differ only in case make .NET throwInvalidOperationException(The JSON property name for 'Twins.A' collides with another property.) when a case-insensitive context is first used; Metano does not report it.
The snake and kebab policies follow .NET's word splitting too: Item_Name →
item_name, Value2 → value2, A1B → a1_b, MyURLValue → my_url_value.
The runtime PropertyNamingPolicy (metano-runtime/system/json) applies the
same rules to a context built by hand, except for characters whose Unicode
category or casing differs between the JS engine and .NET 10 (engine-dependent,
e.g. U+0295 under Bun).
Two properties whose names map to the same JSON name make .NET throw
InvalidOperationException when the context is first used: ID and Id under
camelCase, or an explicit [JsonPropertyName("name")] next to a Name property
the policy renames to name. Metano does not report it yet and emits both.
Where the policy comes from. Metano reads only the
[JsonSourceGenerationOptions] attribute on the context class. Options given to
the context at runtime override that attribute in .NET and are invisible to
Metano: options passed to the context's constructor
(new WebJsonContext(new JsonSerializerOptions(JsonSerializerDefaults.Web))), or
set through ASP.NET Core's JsonOptions / TypeInfoResolverChain. A context
with no attribute that is built with camelCase options writes firstValue in
.NET while Metano emits FirstValue. Put JsonSerializerDefaults.Web (or the
PropertyNamingPolicy) on the attribute so both sides agree.
The runtime SerializerContext accepts custom converters in its options:
import { SerializerContext, type JsonConverter } from "metano-runtime/system/json";
import { Decimal } from "metano-runtime/system/decimal";
const decimalAsString: JsonConverter = {
kind: "decimal",
serialize: (v) => (v as Decimal).toString(),
deserialize: (v) => new Decimal(v as string),
};
// If you construct your context manually:
class MyContext extends SerializerContext {
constructor() {
super({ converters: [decimalAsString] });
}
}The default decimal converter reads a JSON number (or, with
AllowReadingFromString, a JSON string) into a Decimal, and writes it with
its exact digits, as .NET does: serialize returns
JSON.rawJSON(value.toFixed()), which JSON.stringify prints unquoted and
without an exponent.
| C# value | .NET writes | Metano writes |
|---|---|---|
19.99m, -42m |
19.99, -42 |
same |
decimal.MaxValue |
79228162514264337593543950335 |
same |
12345678901234567890.123456789m |
12345678901234567890.123456789 |
same |
0.0000001m |
0.0000001 |
same (decimal.js toString() would print 1e-7) |
decimal.Negate(0m) |
0 |
same |
1.10m, 1.0m, 0.00m |
1.10, 1.0, 0.00 |
1.1, 1, 0 |
The last row is the remaining gap: decimal.js drops trailing zeros (the scale),
so 1.10m is written 1.1. The value is the same; only the text differs.
Cost: writing a 1 MB Order[] with decimal.js prices (bun run bench:json)
takes 5.5–5.7 ms against 4.3 ms with toNumber() on Bun 1.4.2, which pays for
creating the JSON.rawJSON leaves, and the same 8.8–9.1 ms on Node 24.11.
Limits:
deserializereads the treeJSON.parsebuilt, which has already rounded every JSON number to a double, so12345678901234567890.123456789reads as12345678901234567000there. Read the text withdeserializeTextto keep every digit (Exact reads).- Engines without
JSON.rawJSON. The runtime detectsJSON.rawJSONonce when it loads (Node 24 and Bun 1.4.2 have it). Without it, decimals are written withtoNumber(), as before 3.0:7.922816251426434e+28forMaxValue. - Values no
System.Decimalholds (NaN, ±Infinity, a magnitude beyond79228162514264337593543950335) throwJsonExceptionThe value NaN cannot be written as System.Decimal: it is outside the System.Decimal range., on every engine. A value below1e-29is written0, which is what .NET reads for it (1e-400000000would otherwise print 400 million zeros). - A value without
toFixedis written withtoNumber(). A hand-written descriptor withouttypekeeps the raw JSON number or string it read and writes it back as is.
JsonSerializer.deserializeText(text, spec) (and
JsonSerializer.withContext(ctx).deserializeText(text, spec)) reads JSON text
as .NET's JsonSerializer.Deserialize(string, JsonTypeInfo<T>) does:
const order = JsonSerializer.deserializeText(
'{"total":12345678901234567890.123456789}',
JsonContext.default.order,
)!; // the text is not `null`
order.total.toFixed(); // "12345678901234567890.123456789"- Decimals are built from their source digits and rounded as .NET rounds
them: at most 28 decimal places and 96 bits, half to even (
2.5e-28reads as2e-28,1e-29as0) except for a tie at the 30th digit of the text or later, which rounds up (leading fraction zeros count:0.0000000000000000000000000000025e2reads as3e-28), and a value that rounds pastMaxValue(79228162514264337593543950335.5) throwsThe JSON value could not be converted to System.Decimal.. Every other value reads asJSON.parsereads it, custom converters included: adoubleproperty still gets a JSnumber. - 64-bit integers (3.0, 64-bit numbers) are read from
their exact token: digits beyond 2^53 arrive intact, and a number with a
fraction or an exponent (
1.0,1e3) throws, as .NET throws. - The path is chosen per spec. A spec with no
decimaland no 64-bit integer anywhere in its closure readsJSON.parse(text), at the same cost as before. A spec with adecimalreadsJSON.parse(text)too unless the text may hold a number of more than 15 digits, which only the runtime's tokenizer keeps exactly. On a 10 MBOrder[](bun run bench:json, Node 24.11 / Bun 1.4.2), prices of two decimal places read in 123.5 / 83.9 ms against 114.7 / 78.1 ms throughJSON.parse+deserialize; prices of 20 or more significant digits read exactly in 237.9 / 139.4 ms, against 124.0 / 84.1 ms for the inexact tree. - A 64-bit integer costs more. A spec with a
long/ulonganywhere in its closure takes the tokenizer whenever the text may hold a number with a fraction or an exponent — a digit followed by.,eorEanywhere, strings included ("v1.0", a GUID's"3e4f…") — so in practice for most payloads that also carry adouble, adecimalor such strings. Only a text of integers and plain strings keepsJSON.parse. On a 5.8 MB array of{ id: long, x, y, z, w: double }(77 800 items, Node 24.11 / Bun 1.4.2),deserializeTexttakes 72–82 / 41–42 ms, against 37–38 / 22–23 ms for the same payload read through a spec whoseidis not 64-bit (about 2x Node, 1.9x Bun). Nearly all of the difference is the tokenizer itself, which is slower than the engine'sJSON.parse; marking a short fraction (1.5) as non-integer costs one small object and no copy of its text. - Invalid text throws
JsonExceptionwith .NET's reader message ('}' is an invalid start of a value.,Expected depth to be zero at the end of the JSON payload. …), not the engine'sSyntaxError. The runtime accepts whatJSON.parseaccepts, so lone surrogates in strings, which .NET rejects, are read. The text is read whole before the contract, so a syntax error is reported before a contract error that precedes it in the text. - Depth. The limit of 64 counts the containers the contract reads, whichever
path read the text (Errors and limits). The tokenizer
itself stops at 1 000 levels, short of the stack, where
JSON.parsereads on. Which one reads the text depends on its numbers, so the same deeply nested payload can read or throw: a value deeper than 1 000 levels in anobjectslot (which the contract does not count) reads throughJSON.parse, but throwsThe JSON text nests containers deeper than 1000 levels…once the text also holds1.0anywhere (even in a string) and the spec has a 64-bit integer — or a number of 16+ digits and the spec has adecimal. .NET rejects both at its defaultMaxDepthof 64; the two runtime paths are left apart (boundingJSON.parsewould cost every read a walk) and documented here instead.
From spec 012 (3.0.0), every long / ulong (and nint / nuint) property,
element, dictionary value or root carries an int64 descriptor instead of a
primitive one, whatever the read options — including a [Branded] type over
a 64-bit integer, whose descriptor keeps the branded companion factory and CLR
typeName and applies them after the exact read:
{
ts: "id",
json: "id",
type: {
kind: "int64",
numberType: "System.Int64",
typeName: "MyApp.SharedKernel.SnowflakeId",
create: SnowflakeId.from,
},
}Native integers. nint follows long and nuint follows ulong (spec
012 DECIDED-2): the same int64 descriptor, numberType System.Int64 /
System.UInt64, the same exact reads and writes, range checks, dictionary keys
and [Branded] / [InlineWrapper] wrappers. System.Text.Json itself has no
converter for IntPtr / UIntPtr (it throws NotSupportedException for a
property, a root or a dictionary key; measured on .NET 10 and 11), so a payload
for a native integer has no STJ counterpart: the contract is Metano's, and a
rejected value names System.Int64 / System.UInt64 rather than the CLR
System.IntPtr. Each such member and value root warns MS0037 (#561): a
TypeScript client can send a payload the .NET side cannot read.
Writes. The converter writes a bigint through the shared exact-number
writer (writeExactNumber), so JSON.stringify prints the exact digits,
unquoted, byte-identical to System.Text.Json. A rawJSON leaf and a safe
integer write the same way; a JS number beyond Number.MAX_SAFE_INTEGER
throws JsonException (the digits are already gone), and so does a
non-integer number.
Reads from a tree. The converter accepts, in order: a bigint within the
type's range; a rawJSON leaf whose text is an integer token
(1.0 / 1e3 are rejected, -0 reads as 0n); a safe integer number
(read as BigInt(n)); and — when the context reads numbers from strings — a
string in the numbers-from-strings grammar, which now comes
back as a bigint. A number beyond the safe integers throws
JsonException naming deserializeText, because JSON.parse already lost
the digits (spec 012 OQ-3). Anything else throws
The JSON value could not be converted to System.Int64. ( … System.Nullable`1[System.Int64]. for a nullable slot; System.UInt64 for a
ulong).
Reads from text. A root whose closure contains a 64-bit member reads
exactly through deserializeText — the same forward-looking tokenizer the
decimals use — so ids above 2^53 arrive with every digit, in every position
(a property, a long?, an array element, a dictionary value, a [Branded]
id). The tokenizer hands the converter the source text of every number that
is not a short integer token, so the tree rules above apply to the token
itself: 1.0, 1e3 and -0.0 throw, as .NET throws, and -0 reads as 0n
(ulong: throws). A polymorphic int tag written 1.0 or 1e0 throws through
the same path, as .NET throws. The tree path is exact only for bigint and
rawJSON values; see the sample reads in
targets/js/sample-issue-tracker/test/json-int64.test.ts.
Dictionary keys. A 64-bit dictionary key is written as its digits
("1152921504606846977"), as System.Text.Json writes the property name, and
read back as a bigint key — never a rounded number. A long-keyed
dictionary can be a property but not a [JsonSerializable] root (MS0035);
wrap it in a record to put it on the wire.
The JSON.stringify hazard. A transpiled object holding a raw bigint
throws under plain JSON.stringify (Do not know how to serialize a BigInt);
the runtime does not patch BigInt.prototype.toJSON (no global side effects).
The generated context is the supported writer — see When to use
[PlainObject] for the
plain-object rule of thumb.
Migration. The 3.0 items — the type change, the tree leaf, the hazard,
the interop warnings (MS0065) and the runtime helpers that changed meaning
(isInt64 / isUInt64, tryParseInt64, the bigint hash) — are
listed in Migrating to 3.0 and the spec's own migration
section.
Null roots (#268, FR-037). deserialize and deserializeText through a
TypeSpec now return T | null: the JSON text null used to throw and now
returns null, as System.Text.Json does for reference types. Code such as
const order: Order = JsonSerializer.deserialize(data, ctx.order); no longer
compiles under strict. Handle the null, or assert it when the payload can
never be null:
const order = JsonSerializer.deserialize(data, JsonContext.default.order);
if (order === null) {
throw new Error("expected an order");
}
const sure = JsonSerializer.deserialize(data, JsonContext.default.order)!;serialize through a TypeSpec now also accepts a value that may be null
(Order | null), returns null for it, and is then typed
Record<string, unknown> | null; a non-null value keeps the
Record<string, unknown> result. BoundSerializer changes the same way. Struct contracts (record struct) and
value-type roots still throw JsonException for null (Null
roots). Value roots (ValueSpec) already carry | null in
their type argument for a reference type.
Decimals. JsonSerializer.serialize used to return a number for each decimal; it now
returns a JSON.rawJSON leaf, a frozen object whose rawJSON property holds
the text. Only JSON.stringify treats it as a number: structuredClone and
postMessage throw DataCloneError on a tree that holds one, and { ...leaf }
is the plain object {"rawJSON":"2.5"} (measured on Node 24 and Bun 1.4.2).
Stringify the tree before cloning or posting it.
-
JSON.stringify(JsonSerializer.serialize(...))works unchanged and now writes every digit. -
Passing the tree straight back to
JsonSerializer.deserializeworks: the converter reads a leaf from its exact text. -
Code that inspects the tree and expects a
number(typeof json.price === "number", arithmetic on it) must handle the leaf:// TypeScript's lib does not declare JSON.rawJSON / JSON.isRawJSON yet. const { rawJSON } = json.price as { readonly rawJSON: string }; const price = new Decimal(rawJSON); // or Number(rawJSON), which rounds
or register a custom
decimalconverter that returns what the code expects.
Wire format changes (2.10.1 → 3.0). These change the JSON a 3.0 context writes or accepts, so a payload exchanged with a 2.x build can differ:
byte[]is written as base64, as .NET writes it ([1,2,3]→"AQID"). 2.x wrote a number array; a 2.x payload such as{"Data":[1,2,3]}now throwsThe JSON value could not be converted to System.Byte[].(Member selection).- Conditional
[JsonIgnore](WhenWritingNull,WhenWritingDefault,WhenWriting,WhenReading): 2.x left these members out; 3.0 writes and reads them (warningMS0037), so a payload without a non-nullable one throwsMissing required property: "Count".WhenWritingNull(the member's, or the context'sDefaultIgnoreCondition) is mirrored since #667: anullmember is left out of the written JSON, as System.Text.Json does, and the warning is gone. JsonSerializerDefaults.Web: 2.x ignored it; 3.0 writes camelCase names (FirstName→firstName) and reads case-insensitively, numbers from strings included (Web defaults).[JsonDerivedType]on an existing hierarchy: 2.x ignored it; 3.0 writes the tag ({"$type":"cat","Name":"c"}) and requires it only when reading through an abstract or interface base — a concrete base reads without one. A registration the context cannot honor fails the build withMS0032(Polymorphism).- JSON
nullfor a struct property, list or set element, or dictionary value now throwsThe JSON value could not be converted to MyApp.SPoint., as .NET does (Null roots). - Dictionary keys are parsed into their key type
(Dictionary keys, #479): a
Dictionary<int, …>readsMap<number, …>keys (2.x kept the strings"1"), and a name the key type rejects ("x"for anint) now throws. Numeric enum keys are written as member names ("High", 2.x wrote"1") andboolkeys asTrue/False(2.x:true/false), as .NET writes them; 2.x payloads still read.
64-bit integers (spec 012). long / ulong (and nint / nuint) are
bigint now, and the JSON tree changes shape around them
(64-bit numbers):
- Generated types say
bigintwhere 2.x saidnumber(ticks?: bigint). Hand-written TS that passesnumbers failstsc(TS2322 / TS2365): pass5n/BigInt(n), convert withNumber(x). serializereturnsrawJSONleaves for 64-bit values (as for decimals);JSON.stringifyprints them unquoted.structuredCloneof such a tree throwsDataCloneError; stringify the tree first.- Reads beyond 2^53 are exact only through the exact path: a tree the caller
parsed with
JSON.parsealready lost the digits, and anumberleaf beyond the safe integers throws pointing atdeserializeText. - A 64-bit dictionary key is written as its digits and read back as a
bigintkey (2.x kept the key strings, as for every numeric key). JSON.stringifyon a transpiled object with a 64-bit field throws; the generated context is the writer (c.json(dto)in Hono needsJSON.stringify(serializer.serialize(dto, spec))).- Interop declarations (
[Import],[Emit],[External], user[MapMethod]/[MapProperty]templates) exchangebigintwith JavaScript now; the compiler warnsMS0065at each one. - Overflow wraps and
checkedthrows like C# (long.MaxValue + 1islong.MinValue);/by zero throwsDivideByZeroExceptionforlongtoo. - Runtime helpers that keep their name and change meaning:
isInt64/isUInt64test abigintover the wholelong/ulongrange (2.x tested a safe-integernumber),tryParseInt64returns[found, bigint]and takes an optionalNumberStylesvalue (2.x returned anumber), and everybiginthash —HashCode.add,valueHashCode,hashInt64— is the .NET word fold, soBigIntegerhash values computed in 2.x no longer match. - Overload dispatch decides
M(int)vsM(long)bytypeofnow (2.x decided by range), andobject o = 5UL; o is longistruewhere C# saysfalse(a rawbigintreads its range; see bcl-mappings). (int)someDoubletruncates now — floating-point casts were erased in 2.x ((int)3.7was3.7) and saturate like .NET today.
Other changes. Spec 009 changed these too; the first, second and fourth already shipped in 2.x:
- Properties are written most-derived first, as .NET writes them (Inheritance, 2.10.0); compare JSON semantically, not as text.
- The runtime's deserialization errors are
JsonException(orNotSupportedExceptionfor polymorphism), with .NET's messages (Errors and limits, 2.10.0). CatchErroror the new classes instead of matchingExpected object for deserialization. - Text-only changes, read back the same:
TimeOnlywith a fraction is written with seven digits, as .NET writes it ("03:04:05.678"→"03:04:05.6780000"), and[JsonPropertyOrder]reorders the keys. - Generic roots are named after System.Text.Json's
JsonTypeInfonames (ctx.list→ctx.listEpisodeSummary; Roots, 2.8.0); setTypeInfoPropertyNameto choose another name. deserializeTextreads decimals exactly, rounded to 28 decimal places (Exact reads).- The generated code needs
metano-runtime3.0.0 (Runtime version).
When a record extends another transpilable record (of this project or of a
referenced Metano package), the child's TypeSpec references the parent's
spec via a base field:
public record Animal(string Name, int Legs);
public record Dog(string Name, int Legs, string Breed) : Animal(Name, Legs);
[JsonSerializable(typeof(Dog))]
public partial class InheritJsonContext : JsonSerializerContext;get dog(): TypeSpec<Dog> {
return this._dog ??= this.createSpec({
type: Dog,
base: this.animal, // ← Name and Legs come from animal's spec
factory: (p: Record<string, unknown>) => new Dog(p.name as string, p.legs as number, p.breed as string),
properties: [
{ ts: "breed", json: "Breed", type: { kind: "primitive" } },
],
});
}The factory receives every constructor argument, inherited ones included. At
serialize/deserialize time, the runtime walks the base chain
(collectWireProperties) and writes properties in System.Text.Json's order:
the type's own properties first, then its base's, recursively
(new Dog("Rex", 4, "lab") → {"Breed":"lab","Name":"Rex","Legs":4}). A property redeclared in a derived type
(override or new) under the same JSON name is written once, at the
most-derived declaration's position and with its type; an override renamed
with [JsonPropertyName] is written under both names, as STJ does. When the
base emits no spec ([Ignore], a non-transpiled base), its properties are
inlined into the derived spec in the same order. Reading does not depend on key
order. The exported collectProperties still lists properties base-first.
A [JsonIgnore] override hides every base declaration of that property, as in
System.Text.Json, which neither writes nor reads it. A linked spec records the
hidden members in ignoredProperties (TS names, e.g. ignoredProperties: ["name"]); the base spec keeps the property for its own instances. The
factory of the derived type then receives no value for it.
A class or record that carries at least one [JsonDerivedType] (with or
without [JsonPolymorphic]) is polymorphic, as in System.Text.Json. Only the
type's own attributes count (both are Inherited = false).
[JsonPolymorphic(TypeDiscriminatorPropertyName = "kind")]
[JsonDerivedType(typeof(ImageClip), "image")]
[JsonDerivedType(typeof(SilenceClip), "silence")]
public abstract record Clip(double Seconds);
public sealed record ImageClip(string Path, double Seconds) : Clip(Seconds);
public sealed record SilenceClip(double Seconds) : Clip(Seconds);
public sealed record Timeline(string Name, Clip Main, IReadOnlyList<Clip> Clips);
[JsonSerializable(typeof(Timeline))]
public partial class StudioJsonContext : JsonSerializerContext;The generated context adds a getter for every registered type (here
imageClip and silenceClip, although no root names them) and ends the
base's spec with a data-only polymorphism member:
get clip(): TypeSpec<Clip> {
return this._clip ??= this.createSpec({
type: Clip,
factory: (p: Record<string, unknown>) => {
throw new Error("Cannot deserialize abstract type 'Clip' directly; deserialize it through a polymorphic spec.");
},
properties: [{ ts: "seconds", json: "Seconds", type: { kind: "primitive" } }],
polymorphism: {
discriminator: "kind", // verbatim, never renamed by a naming policy
abstract: true, // the C# base is abstract
derived: [
{ tag: "image", spec: () => this.imageClip },
{ tag: "silence", spec: () => this.silenceClip },
],
},
});
}- Tags. A string tag prints as a string, an int tag as a number
(
[JsonDerivedType(typeof(IntA), 1)]→{ tag: 1, … }and{"$type":1,"X":5}on the wire); an untagged registration has notag. A base that registers itself links to its own getter ({ tag: "b", spec: () => this.sBase }). The default discriminator is$type. When no registration has a tag, System.Text.Json reads no metadata at all: a concrete base reads its own contract ($-prefixed keys are plain data), and an abstract base throwsNotSupportedExceptionDeserialization of interface or abstract types is not supported. Type 'UAB'.; writes still dispatch. - Options.
unknownDerivedType: "fallBackToBaseType"/"fallBackToNearestAncestor"andignoreUnrecognizedTags: trueare emitted only when the attribute sets them. UnderFallBackToNearestAncestoran abstract registered type is allowed and markedabstract: trueon its entry: it is a write target for its unregistered subtypes, and reading its tag throwsNotSupportedExceptionDeserialization of interface or abstract types is not supported. Type 'AMid'., as System.Text.Json does (an abstract registered type that is itself polymorphic reports its own missing tag instead). - Closed generic bases.
[JsonDerivedType(typeof(GDer), "g")]onGBase<T>withGDer : GBase<int>: the attributes are read fromGBase<T>, and every construction the context dispatches through gets its own polymorphic spec (get gBaseInt32(): TypeSpec<GBase<number>>), whichGDer'sbaselink names. - Only where the context dispatches. A base reached only through a
derived type's
baselink (for example a roottypeof(GDer)alone) gets a plain spec with nopolymorphism, no registrations and no diagnostics: System.Text.Json never builds its polymorphism either. - Abstract factory. The factory of an abstract polymorphic base stays a throwing factory, which a polymorphic read never calls; its message tells to read through the polymorphic spec. A non-polymorphic abstract type keeps the message "polymorphic JSON deserialization is not supported yet".
- Diagnostics.
MS0032(error, at the attribute) rejects a registration that is generic, not assignable to the base (to each construction the context dispatches through, for a generic base), not transpiled in its declaring assembly, abstract withoutFallBackToNearestAncestor, or a repeated type or tag; the registration is left out ofderived. It also rejects, leaving the base withoutpolymorphism, a sealed base, a[JsonPolymorphic]without any[JsonDerivedType], a reserved discriminator ($id,$ref,$values), and a JSON property of a contract written with a tag that is named like the discriminator (System.Text.Json throws) or integer-like (JavaScript would write it before the tag); System.Text.Json rejects all of them too.MS0033(warning) flags an untagged registration (it reads back as a concrete base, and cannot be read through an abstract one) and a registered type that declares its own[JsonDerivedType]s (not re-dispatched through the outer base); both behave exactly as in System.Text.Json. - Known gap. A closed generic registration
(
[JsonDerivedType(typeof(GenD<int>), "g")]) isMS0032, although System.Text.Json accepts it. - Read options. The context's
AllowOutOfOrderMetadataPropertiesoption is mirrored in itsreadOptions(details).
With the Clip context above, new ImageClip("a.png", 1.5) through
ctx.clip writes {"kind":"image","Path":"a.png","Seconds":1.5}, and reading
that text through ctx.clip returns an ImageClip. A Timeline writes the tag
inside each Clip-typed property and element:
{"Name":"t","Main":{"kind":"image","Path":"a","Seconds":1},"Clips":[{"kind":"image","Path":"b","Seconds":2}]}.
These come from the conformance sample (samples/SampleJsonContracts); each
result is a manifest row that .NET and the TypeScript output both pass.
[JsonPolymorphic(UnknownDerivedTypeHandling = JsonUnknownDerivedTypeHandling.FallBackToNearestAncestor)]
[JsonDerivedType(typeof(UNearA), "a")]
[JsonDerivedType(typeof(UNearAbs), "abs")]
public abstract record UNear(int A);
public record UNearA(int A, int B) : UNear(A);
public abstract record UNearAbs(int A) : UNear(A);
public sealed record UNearB(int A, int B, int C) : UNearA(A, B); // not registered
[JsonPolymorphic(UnknownDerivedTypeHandling = JsonUnknownDerivedTypeHandling.FallBackToBaseType)]
[JsonDerivedType(typeof(UBaseA), "a")]
public abstract record UBaseH(int A);
public sealed record UBaseX(int A, int X) : UBaseH(A); // not registered
[JsonPolymorphic(TypeDiscriminatorPropertyName = "k", IgnoreUnrecognizedTypeDiscriminators = true)]
[JsonDerivedType(typeof(IgnDer), "d")]
public record IgnBase(int V);
[JsonSourceGenerationOptions(AllowOutOfOrderMetadataProperties = true)]
[JsonSerializable(typeof(Clip))]
public partial class OutOfOrderJsonContext : JsonSerializerContext;// in the spec of UNear
polymorphism: {
discriminator: "$type",
abstract: true,
derived: [
{ tag: "a", spec: () => this.uNearA },
{ tag: "abs", spec: () => this.uNearAbs, abstract: true },
],
unknownDerivedType: "fallBackToNearestAncestor",
},
// in the spec of IgnBase
polymorphism: {
discriminator: "k",
derived: [{ tag: "d", spec: () => this.ignDer }],
ignoreUnrecognizedTags: true,
},
// in OutOfOrderJsonContext
protected override get readOptions(): JsonReadOptions {
return { allowOutOfOrderMetadataProperties: true };
}| Call | Result |
|---|---|
write new UNearB(1, 2, 3) through uNear |
{"$type":"a","B":2,"A":1}: the nearest registered ancestor, UNearA, and its contract |
read {"$type":"a","B":2,"A":1} through uNear |
a UNearA |
read {"$type":"abs","A":1} through uNear |
NotSupportedException Deserialization of interface or abstract types is not supported. Type 'UNearAbs'. |
write new UBaseX(1, 2) through uBaseH |
{"A":1}: the base contract, no tag |
read {"k":"zzz","V":1} through ignBase |
an IgnBase: the unknown tag is ignored |
read {"Path":"a","kind":"image","Seconds":1} through OutOfOrderJsonContext's clip |
an ImageClip: the tag may follow other keys |
An untagged registration ([JsonDerivedType(typeof(NA))]) writes the
registered type's contract with no tag and reads back as the base, so it warns
MS0033, as does a registered type with its own [JsonDerivedType]s
(NMid under NBase: {"t":"mid","B":2,"A":1} is written, and an NLeaf
through NBase throws Runtime type 'NLeaf' is not supported by polymorphic type 'NBase'., as in .NET).
[JsonDerivedType(typeof(Sq), "sq")]
[JsonDerivedType(typeof(Circle), "circle")]
public interface IShape { double Area { get; } }
public sealed record Sq(double Side) : IShape { public double Area => Side * Side; }
public sealed record Circle(double Radius) : IShape { public double Area => 3 * Radius * Radius; }
[PlainObject]
[JsonDerivedType(typeof(Point), "point")]
[JsonDerivedType(typeof(Point3), "point3")]
public abstract record Shape;
[PlainObject] public record Point(double X) : Shape;
[PlainObject] public sealed record Point3(double X, double Y, double Z) : Point(X);get iShape(): TypeSpec<IShape> {
return this._iShape ??= this.createSpec({
factory: (p: Record<string, unknown>) => {
throw new Error("Cannot deserialize interface type 'IShape' directly; deserialize it through a polymorphic spec.");
},
properties: [{ ts: "area", json: "Area", type: { kind: "primitive" } }],
polymorphism: {
discriminator: "$type",
abstract: true,
typeName: "IShape",
derived: [{ tag: "sq", spec: () => this.sq }, { tag: "circle", spec: () => this.circle }],
},
});
}
get shape(): TypeSpec<Shape> {
return this._shape ??= this.createSpec({
factory: (p: Record<string, unknown>) => {
throw new Error("Cannot deserialize abstract type 'Shape' directly; deserialize it through a polymorphic spec.");
},
properties: [],
polymorphism: {
discriminator: "$type",
abstract: true,
typeName: "Shape",
derived: [
{ tag: "point", spec: () => this.point, test: isPoint },
{ tag: "point3", spec: () => this.point3, test: isPoint3 },
],
testOrder: [1, 0],
},
});
}
get point3(): TypeSpec<Point3> {
return this._point3 ??= this.createSpec({
base: this.point,
factory: (p: Record<string, unknown>) => ({ x: p.x as number, y: p.y as number, z: p.z as number }),
properties: [
{ ts: "y", json: "Y", type: { kind: "primitive" } },
{ ts: "z", json: "Z", type: { kind: "primitive" } },
],
});
}The synthesized guard in point.ts:
export function isPoint(value: unknown): value is Point {
if (value == null || typeof value !== "object") {
return false;
}
const v = value as any;
return typeof v.x === "number";
}- Interface bases. A C# interface with
[JsonDerivedType]is an abstract base: its spec has notype(a TS interface has no constructor), a throwing factory, the interface's own and inherited properties (written underFallBackToBaseType, in System.Text.Json's order: the interface first, then the interfaces it extends, sorted topologically), andtypeNamefor the messages. Class variants are dispatched by constructor and have nobaselink to the interface.Sq(2)throughIShapewrites{"$type":"sq","Side":2,"Area":4}, as System.Text.Json does. An interface registered as a derived type isMS0032; an interface without[JsonDerivedType]is still not a JSON contract (MS0035as a root). - Non-polymorphic interface members. A member typed as an interface without
[JsonDerivedType]claims a spec with the interface's properties and notype, as System.Text.Json writes it:Dashboard("t", new Gauge(5, "kg"))throughIGauge Mainwrites{"Title":"t","Main":{"Level":5}}. Reading a JSON object into it throwsNotSupportedExceptionDeserialization of interface or abstract types is not supported. Type 'SampleJsonContracts.IGauge'., as does reading into a non-polymorphic abstract class;nullreads asnull(#502). - Synthesized guards. Every
[PlainObject]type a[JsonDerivedType]registers, and every concrete[PlainObject]type that is itself polymorphic, gets anisTguard in its own file, built like a[GenerateGuard]guard (the predicate only, withoutassertT), so every registered[PlainObject]type exports anisTfunction from its module, whether or not a context uses it. The context imports it as a value (import { isPoint, type Point } from "./point";Shape.isCirclefor a nested type; from the package for a library variant, whose own build emits the guard). A guard checks a member whose type has no guard of its own for presence (v.from != null). - Write order. Guards run only for plain objects (prototype
Object.prototypeornull); class instances never reach them. A variant whose guard requires a subset of another variant's members is tested after it:Pointaccepts everyPoint3, sotestOrder: [1, 0]testsPoint3first, and{ x: 1, y: 2, z: 3 }writes{"$type":"point3","Y":2,"Z":3,"X":1}.testOrderis omitted when it equals attribute order. - Concrete
[PlainObject]base. A concrete base that does not register itself carries its own guard asbaseTest: a plain object no variant guard accepts is written as the base, with no tag, whenbaseTestaccepts it ({"Name":"a"}, as System.Text.Json writes anAnimal); otherwise it is an unregistered runtime type namedObject(NotSupportedExceptionRuntime type 'Object' is not supported by polymorphic type 'Animal'.underfailSerialization). A self-registered base is an entry with its owntest. - Reads dispatch on the tag, as for classes; a
[PlainObject]entry's factory builds an object literal with the inherited members too. - Diagnostics.
MS0032rejects two[PlainObject]variants whose guards accept each other's values (the same required members with compatible test kinds, or no required member at all), variants with no consistent test order, and a variant whose guard accepts every value of a concrete base written throughbaseTest(Dog2(string Name, int? Bark)underAnimal2(string Name)would capture everyAnimal2), leaving the base withoutpolymorphism. It also rejects a registered[PlainObject]type that gets no guard ([Import],[ExportedAsModule],[NoContainer]). Members of the same name with different kinds (stringvsnumber), or different[Discriminator]literals, tell variants apart. - Divergences. A plain object carries no runtime type: an unregistered C#
subtype whose shape satisfies a registered variant's guard is written as
that variant, and one whose shape passes the base's
baseTestis written as the base (Cat4→{"Name":"c"}), where System.Text.Json throwsNotSupportedException; the runtime type name in the error isObject. - Known gap. A generic concrete
[PlainObject]base gets no guard, so nobaseTest(generic[PlainObject]contracts do not compile undertsgoyet anyway).
- Write. A class instance is matched by its constructor: a registered type
(the base too, when it registers itself) writes its tag as the first key,
then its contract (
{"kind":"image","Path":"a.png","Seconds":1.5}); an unregistered base instance is written with no tag; any other runtime type followsunknownDerivedType—failSerialization(default) throwsNotSupportedExceptionRuntime type 'X' is not supported by polymorphic type 'Clip'.,fallBackToBaseTypewrites the base contract with no tag,fallBackToNearestAncestorwrites the nearest registered ancestor class (or the base). A plain object has no runtime type: it is matched by thetestguards of[PlainObject]variants, intestOrder. A derived contract reached this way is never dispatched again, even when it is polymorphic too. - Read. The tag counts only under its exact name and only as the first key
(anywhere with
readOptions: { allowOutOfOrderMetadataProperties: true }, which a context declaringAllowOutOfOrderMetadataProperties = trueemits). A string tag never matches a number tag (1≠"1"). An unknown tag throwsJsonExceptionRead unrecognized type discriminator id 'video'.unlessignoreUnrecognizedTagsis set; a missing tag reads a concrete base and, on an abstract or interface base, throwsNotSupportedExceptionThe JSON payload for polymorphic interface or abstract type 'Clip' must specify a type discriminator.; a tag that is neither a string nor a number throwsJsonExceptionThe '$id', '$ref' or '$type' metadata properties must be JSON strings. Current token type is 'Null'., and a number outsideInt32throwsThe JSON value could not be converted to Clip.. - Misplaced metadata. A later tag on a concrete base throws
JsonExceptionThe metadata property is either not supported by the type or is not the first property in the deserialized JSON object.(on an abstract base it is a missing tag), and so do$id/$refand a later$values(a leading$valueshas its own message). Any other key that starts with$throwsProperties that start with '$' are not allowed in types that support metadata. …. These checks apply only to polymorphic specs. JS enumerates array-index keys ("0") first, so an index key written before the tag goes unnoticed, where STJ rejects it. - Abstract registrations. An entry marked
abstract: trueis a nearest-ancestor target on write; reading its tag throws theNotSupportedExceptionabove ($id,$refor$valuesright after the tag throw the misplaced-metadataJsonExceptionfirst). - Dispatch applies at the root and through
ref,array,hashSet,mapandnullabledescriptors, soList<Clip>,Clip[]roots andClip-typed properties all write and read the tag. A custom converter registered forkind: "ref"replaces it, as before.
Deserialization errors are JsonException (exported from
metano-runtime/system/json, extends Error, name === "JsonException").
Messages follow System.Text.Json without its Path / LineNumber suffix:
| Input | Message |
|---|---|
| A non-object JSON value (or an array) for an object contract | The JSON value could not be converted to Episode. (Object for a [PlainObject] contract, which has no constructor); JSON null reads as null instead (Null roots) |
JSON null at a struct contract or a value-type root (valueType: true), or for a struct property, element or dictionary value |
The JSON value could not be converted to MyApp.SPoint. (Null roots) |
JSON null for an ImmutableArray<T> (a struct) root, element or dictionary value |
The JSON value could not be converted to System.Collections.Immutable.ImmutableArray`1[System.Int32].; for a property the runtime names the declaring contract where STJ names the ImmutableArray type (#713) |
| A missing non-nullable property | Missing required property: "title" (STJ uses the default value unless the member is required; a documented divergence). A nullable member declared required or [JsonRequired] reads null when missing, where STJ throws (both warn MS0037) |
An invalid base64 text, or a non-string JSON value, for a byte[] |
The JSON value could not be converted to System.Byte[]. (STJ names the declaring type for a constructor-bound property) |
| A non-array JSON value for an array, list or set | Expected array for deserialization, got object (STJ names the CLR collection type) |
| A non-object JSON value (or an array) for a dictionary | Expected object for deserialization, got array |
| A numeric JSON string the grammar rejects, when the context reads numbers from strings | The JSON value could not be converted to System.Int32. (STJ names the declaring type for a constructor-bound property) |
| An unknown string enum value | Invalid enum value: … (STJ: The JSON value could not be converted to Color.) |
A numeric enum value that is not an integer of the underlying type (1.5, 300 for a byte enum, a string) |
The JSON value could not be converted to MyApp.Color.; any integer in range reads, member or not (7 reads as (Color)7, a [Flags] combination as itself), as System.Text.Json reads it (#369) |
| More than 64 nested containers on read | The maximum configured depth of 64 has been exceeded. Cannot read next JSON object. (… JSON array. for an array) |
| More than 64 nested containers on write, or an object cycle | A possible object cycle was detected. This can either be due to a cycle or if the object depth is larger than the maximum allowed depth of 64. Consider using ReferenceHandler.Preserve on JsonSerializerOptions to support cycles. |
The depth limit is System.Text.Json's default MaxDepth of 64: 64 nested
objects, arrays and dictionaries are written and read, the 65th throws; scalars
never count. On read, only the containers the contract visits count; a deeply
nested value under a key the contract does not declare is skipped without being
counted, where the STJ reader would throw, also through deserializeText
(Exact reads).
Invalid JSON text passed to deserializeText throws JsonException with the
STJ reader's message ('x' is an invalid start of a value.); deserialize
takes an already parsed value, so JSON.parse throws its own SyntaxError
first.
On write, Metano is a hybrid of STJ's two modes. Its boundary is the one of a
source-generated context at its default (fast-path) settings, which also writes
a scalar inside the 64th container and throws InvalidOperationException
CurrentDepth (64) is equal to or larger than the maximum allowed depth of 64. … at the 65th. Its exception and message are the metadata / reflection
mode's JsonException above, which that mode already throws for a non-null
scalar written inside the 64th container. A custom converter that serializes a
separate root inside a call inherits the outer depth, where STJ starts that
root at depth 0.
Ignored properties: a constructor parameter bound to a [JsonIgnore] property
receives undefined (STJ passes default(T)), and a [JsonIgnore] new
(non-override) redeclaration does not hide the base declaration, which is then
written from the single TS member that holds the derived value, at the base's
position (STJ writes the base value at the redeclaration's position).
Constructor access: a class with a TypeSpec in the context is passed as
type: T and built by factory: (p) => new T(...), both outside its class
body, so its constructor stays public even when C# declares it private or
protected (warning MS0061, baseline FR-049, #432). A class with two or more constructors is
built through the factory of its [JsonConstructor] overload instead (Money.fromAmount(…),
spec 013 FR-035); that factory is emitted public, with MS0061, when its overload is not.
Other classes keep their constructor's
private / protected modifier. A context that claims a type from a referenced
package with no public constructor does not type-check, because that package
decided the modifier when it was transpiled; the transpiler reports MS0062 at
the context. It cannot see a type the package kept public through MS0061,
which warns although the package emitted a public constructor. A project
reference loads as source and is otherwise judged exactly; a binary reference
(a DLL or a package) is read from metadata, which also cannot tell an abstract
class's C# 12 primary constructor from a declared protected one.
The runtime compiles each spec once, on first use, into a cached plan. Specs that the transpiler generates always meet its assumptions. A spec written by hand must meet them too:
- Property converters are resolved when the spec is first used. A malformed descriptor fails then, even when the value being converted lacks that property.
- A
refdescriptor'sspec()thunk is called once and its result is kept. It must return the same spec every time, as the generated??=context getters do. - A
refthat points at a raw spec object instead of the context getter does not inherit the context's read options, because the context attaches them increateSpec. This behavior predates the plans.
The conformance sample (samples/SampleJsonContracts) runs one manifest of
cases through the real System.Text.Json source-generated contexts and through
the generated TypeScript; both sides must agree, row by row, except for the
differences below. The full list, with the measured .NET behavior and the
manifest row of each, is the
Documented divergences table of spec 009.
Lost to JSON.parse. deserialize receives a tree, so lexical facts of
the text are gone:
- duplicate keys: the last value wins, including a duplicate discriminator
(STJ throws) and an earlier invalid value of the same property
(
{"price":1e30,"price":1}reads1); in a case-insensitive context{"count":1,"COUNT":2,"count":3}reads2(STJ:3); - an int tag written
1.0or1e0is accepted (STJ throws), and so is alongwritten1.0(read as1n);deserializeTextrejects both for a spec with a 64-bit integer in its closure (64-bit numbers); - an array-index key (
"0") written before the tag is not seen as out of order; - a
decimaljust pastMaxValue, or with more than 15 significant digits, is already a double: usedeserializeText(Exact reads); - lone surrogates in strings are accepted, and a syntax error is reported before a contract error earlier in the text.
Written text. The items below describe JSON.stringify(JsonSerializer.serialize(…)),
the tree path TypeScript callers use. serializeText (the target of a transpiled
JsonSerializer.Serialize, above) writes .NET's
text instead for NaN / ±Infinity (it throws ArgumentException) and for numbers
(1E+21, -0).
decimaldrops trailing zeros (1.10m→1.1), and engines withoutJSON.rawJSONwritetoNumber()(Decimals);NaN/±Infinityare writtennull(STJ throws withoutAllowNamedFloatingPointLiterals);1E+21and-0print as1e+21and0;TimeSpan(PT1H2M3S) andDateTimeOffset(…+00:00[UTC]) are written as Temporal strings, which .NET does not read, and vice versa;[StringEnum]values are strings, where .NET writes numbers withoutJsonStringEnumConverter;- dictionary keys that are array indices (
"0"to"4294967294", of any integer, enum or string key type) come out in JS order, before every other key, and so does a dictionary read and written back:{"18446744073709551615":null,"1":-1}round-trips as{"1":-1,"18446744073709551615":null}(#562; the texts stay mutually readable, row V17). A JS object cannot hold such keys in insertion order, and writing ordered entries would need a writer that does not build the treeJSON.stringifyprints;Stack<T>is written in array order; doubledictionary keys print asString()prints them (1e+21,0for-0; .NET:1E+21,-0), aNaNkey is written (.NET throws), adecimalkey drops trailing zeros (1.10→1.1), aGuidkey keeps the case it holds, and a[Flags]combination of a numeric enum key is written as its number (.NET:A, B);- a
nullbyte[]is writtennull(the .NET source-generated fast path writes""); - a
[JsonIgnore] newredeclaration writes the derived value at the base's position.
Reading.
- A missing non-nullable property throws
Missing required property: "…"; .NET uses the default value unless the member isrequired. A missing nullablerequired/[JsonRequired]member readsnull(MS0037). - JSON
nullfor anint,bool, enum, branded or temporal property, element or dictionary value readsnull(.NET throws); a value-type custom converter never seesnull(Null roots). - An unknown numeric enum value throws (
7reads as(Color)7in .NET); unknown string enum values and numeric enums read from strings throw with Metano's own messages. - Dictionary keys: a
[StringEnum]key does not read its member's number (.NET reads"1"); enum keys use the TS member names, so a member renamed with[Name]or[JsonStringEnumMemberName]does not read the name .NET writes; two names that read as one key keep the one JS enumerates last (Dictionary keys); a temporal key reads whatever itsparseaccepts (Temporal.PlainDate.fromtakes2024-01-02T00:00, .NET throws). setmembers are assigned after construction in wire order, not in the payload's order; a constructor parameter bound to an ignored property getsundefined.- The depth limit counts only the containers the contract visits, and
deserializeTextstops at 1 000 nested levels (Errors and limits). - Two property names that differ only in case in a case-insensitive context are not reported (.NET throws on first use); case-insensitive matching uses the JS engine's Unicode tables.
Polymorphism.
- A plain object carries no runtime type: an unregistered C# subtype of a
[PlainObject]hierarchy is written as the registered variant (or the concrete base) its shape matches, and the error namesObject(details). - A closed generic registration (
[JsonDerivedType(typeof(GenD<int>), "g")]) isMS0032; integer-like property names in a tagged contract areMS0032. - Messages name types without their namespace (
'Clip', .NET:'SampleJsonContracts.Clip').
Messages and limits. Messages carry no Path / LineNumber suffix; a
constructor-bound property's conversion error names the property's type
(System.Int32, System.Byte[]) where .NET names the declaring type; the
collection errors keep Metano's Expected array for deserialization, got …
text; the write depth limit raises the metadata mode's JsonException at the
fast path's boundary; a custom converter that serializes a separate root
inherits the outer depth.
Options. Options Metano does not mirror are reported with MS0037
(Member selection); options given to the context at
runtime are invisible to the transpiler (Web defaults).
Both are valid ways to handle JSON data:
[PlainObject] |
JsonSerializerContext |
|---|---|
Emits a TS interface, no class |
Emits a full class with spec-driven serialization |
Use JSON.stringify/parse directly |
Use JsonSerializer.serialize/deserialize |
| No naming policy handling | Full naming policy + per-property overrides |
| No nested type conversion | Handles Temporal, Decimal, Map, HashSet, branded types, etc. |
| Fast path for simple DTOs | Correct handling of non-JSON-safe types |
Rule of thumb:
- Simple DTO with only primitives and arrays of primitives? →
[PlainObject] - Rich domain type with dates, decimals, branded IDs, maps? →
JsonSerializerContext
64-bit fields. From spec 012 (3.0.0) a long / ulong field of a
[PlainObject] type is a TS bigint (ticks?: bigint, FR-060), and
JSON.stringify throws on such an object — JavaScript has no JSON form for a
bigint (TypeError: Do not know how to serialize a BigInt). The supported
writer is the generated JsonSerializerContext, whose int64 descriptor
writes the exact digits; use JSON.stringify(serializer.serialize(dto, spec))
when a framework helper calls JSON.stringify for you. Keep such DTOs
number-only (use int / double) when they must survive plain
JSON.stringify.
- Attribute Reference —
[PlainObject]details - BCL Type Mappings — how types are classified
- Spec 009 — System.Text.Json-faithful JSON contracts: requirements, decisions and the documented divergences
- Diagnostic catalog —
MS0032–MS0037 - Feature support matrix — current support status of the serialization features
samples/SampleJsonContracts— the conformance sample checked against System.Text.Json in CI
A list, set, queue, stack or dictionary property deserializes into the metano-runtime
collection class (List, HashSet, Queue, Stack, Dictionary) and serializes through
iteration; the wire format is the one System.Text.Json writes (arrays for the sequence
kinds, an object for a dictionary; a repeated dictionary key keeps its last value). The
context writes a create closure per collection descriptor (create: (items) => List.of(items))
so system/json imports no collection class. When the compilation asks a runtime question
about the collection kind (see BCL mappings),
the closure passes the type arguments (List.of(items, [Int32Type])), so a deserialized
List<int> is a List<int> and not a List<string> at a type test.
A TypeSpec for a class, record or struct contract also carries
runtimeType: () => Item.$runtimeType, the thunk of the type's runtime descriptor, and the
class emits its $runtimeType getter for it (a [PlainObject] or interface contract has no
class and no thunk). Nothing in the serializer reads the link yet; it costs the class's
descriptor literal only where the class is bundled.