{"slug":"crystaljson-2","title":"crystaljson","summary":"How to use CrystalJson, the custom JSON library in SnowBank.Core (namespace SnowBank.Data.Json). Covers the JsonValue DOM (JsonObject / JsonArray / JsonString / JsonNumber / JsonBoolean / JsonNull / JsonDateTime), the read-only vs mutable model, the CrystalJson static API (Serial","platform":"Claude","tags":[],"authorName":"LLM Mart","authorSlug":"llm-mart","score":0,"source":"github","price":null,"verified":false,"createdAt":"2026-09-27T20:59:40.480665Z","repo":{"url":"https://github.com/SnowBankSDK/foundationdb-dotnet-client","stars":158,"forks":33,"license":"BSD-3-Clause","updatedAt":"2026-11-10T19:28:00Z"},"bodyHtml":"<hr>\n<h2>name: crystaljson\ndescription: &gt;-\nHow to use CrystalJson, the custom JSON library in SnowBank.Core (namespace SnowBank.Data.Json). Covers the JsonValue\nDOM (JsonObject / JsonArray / JsonString / JsonNumber / JsonBoolean / JsonNull / JsonDateTime), the read-only vs mutable\nmodel, the CrystalJson static API (Serialize / Parse / Deserialize) and CrystalJsonSettings, the Roslyn source generator\nfor fast reflection-free serializers and read-only/writable proxies ([CrystalJsonConverter] / [CrystalSerializable]),\nthe IJsonSerializable / IJsonPackable / IJsonDeserializable interfaces, MutableJsonValue / ObservableJsonValue and\nJsonPath. Use whenever code parses, builds, reads, mutates, or serializes JSON with these types, reads optional fields\nwith defaults, declares a generated JSON converter/proxy, or implements custom JSON (de)serialization. Use it even when\nthe request only says \"serializer\", \"converter\", or \"serialize/deserialize a record, document, or model\" without naming\nJSON: in SnowBank-based code (document stores, sync layers, Layers, models) document and message (de)serialization goes through\nCrystalJson, not System.Text.Json or Newtonsoft.</h2>\n<h1>CrystalJson (SnowBank.Data.Json)</h1>\n<p>CrystalJson is a high-performance, allocation-conscious JSON stack. It is <strong>not</strong> <code>System.Text.Json</code> or Newtonsoft -\nthe type names look familiar (<code>JsonObject</code>, <code>JsonArray</code>, ...) but the API is different. The namespace is\n<code>SnowBank.Data.Json</code>. Add <code>using SnowBank.Data.Json;</code>.</p>\n<p>There are <strong>two layers</strong>, used together:</p>\n<ol>\n<li><strong>The DOM</strong> - <code>JsonValue</code> and its subtypes. A mutable-or-immutable tree you build, parse, navigate, and serialize.\nUse it for schemaless / dynamic JSON (config, arbitrary documents, change records).</li>\n<li><strong>The source generator</strong> - <code>[CrystalJsonConverter]</code> + <code>[CrystalSerializable(typeof(T))]</code> generate fast,\nreflection-free, AOT-friendly converters for your POCOs, plus typed <strong>read-only / writable proxies</strong> over the DOM.\nUse it for your domain types.</li>\n</ol>\n<p><code>CrystalJson</code> (static class) is the entry point for serialize/parse/deserialize regardless of layer.</p>\n<hr>\n<h2>1. The JsonValue DOM</h2>\n<p><code>JsonValue</code> is the abstract base. Concrete types and their <code>JsonType</code>:</p>\n<table>\n<thead>\n<tr>\n<th>Type</th>\n<th><code>JsonType</code></th>\n<th>Notes</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td><code>JsonObject</code></td>\n<td><code>Object</code></td>\n<td>key -&gt; value map; mutable <strong>or</strong> read-only</td>\n</tr>\n<tr>\n<td><code>JsonArray</code></td>\n<td><code>Array</code></td>\n<td>ordered list; mutable <strong>or</strong> read-only</td>\n</tr>\n<tr>\n<td><code>JsonString</code></td>\n<td><code>String</code></td>\n<td>immutable</td>\n</tr>\n<tr>\n<td><code>JsonNumber</code></td>\n<td><code>Number</code></td>\n<td>immutable; small ints cached</td>\n</tr>\n<tr>\n<td><code>JsonBoolean</code></td>\n<td><code>Boolean</code></td>\n<td>immutable; only <code>True</code>/<code>False</code> singletons</td>\n</tr>\n<tr>\n<td><code>JsonDateTime</code></td>\n<td><code>DateTime</code></td>\n<td>immutable; serialized as an ISO string</td>\n</tr>\n<tr>\n<td><code>JsonNull</code></td>\n<td><code>Null</code></td>\n<td>three distinct singletons (below)</td>\n</tr>\n</tbody>\n</table>\n<p><strong>The three nulls - this trips people up:</strong></p>\n<ul>\n<li><code>JsonNull.Null</code> - an <strong>explicit</strong> null that was present in the JSON (<code>{\"x\": null}</code>).</li>\n<li><code>JsonNull.Missing</code> - a field that <strong>was not there</strong> (<code>obj[\"absent\"]</code>) or an out-of-range array read.</li>\n<li><code>JsonNull.Error</code> - result of an <strong>invalid</strong> access (e.g. indexing a non-array).</li>\n</ul>\n<p>All three report <code>value.IsNull == true</code>. Distinguish them with <code>value.IsNullOrMissing()</code>, <code>value.IsMissing()</code>,\n<code>value.IsError()</code>, or <code>ReferenceEquals(value, JsonNull.Missing)</code>. Parsing an empty/whitespace/<code>null</code> input gives\n<code>JsonNull.Missing</code>; parsing the literal <code>\"null\"</code> gives <code>JsonNull.Null</code>.</p>\n<p>Other useful singletons: <code>JsonBoolean.True/False</code>, <code>JsonNumber.Zero/One</code>, <code>JsonObject.ReadOnly.Empty</code>,\n<code>JsonArray.ReadOnly.Empty</code>.</p>\n<hr>\n<h2>2. Read-only vs mutable - the core mental model</h2>\n<p>This is the most important concept. <code>JsonObject</code> and <code>JsonArray</code> can each be <strong>mutable</strong> or <strong>read-only</strong>\n(<code>value.IsReadOnly</code>). Scalars (string/number/bool/null/datetime) are always read-only.</p>\n<ul>\n<li><strong>Mutating a read-only container throws</strong> <code>InvalidOperationException</code> (\"Cannot mutate ... because it is marked as\nread-only\").</li>\n<li>A read-only value is safe to <strong>cache and share across threads</strong>.</li>\n<li>Conversions:\n<ul>\n<li><code>value.ToReadOnly()</code> - returns self if already read-only, else a deep read-only copy.</li>\n<li><code>value.ToMutable()</code> - returns a mutable copy (minimal copying); use before editing a possibly-frozen value.</li>\n<li><code>value.Copy(deep: true, readOnly: false)</code> - explicit copy.</li>\n<li><code>value.Freeze()</code> - freezes in place (only on values you exclusively own).</li>\n</ul>\n</li>\n</ul>\n<p><strong>Build mutable, then optionally freeze; or build read-only directly with the <code>ReadOnly</code> factory.</strong></p>\n<pre><code>using SnowBank.Data.Json;\n\n// mutable, with the Create factories (the default pattern; implicit conversions cover scalars)\nvar obj = JsonObject.Create([\n    (\"name\", \"Alice\"),\n    (\"age\", 30),\n    (\"tags\", JsonArray.Create(\"admin\", \"user\")),\n    (\"point\", JsonObject.Create([ (\"x\", 1), (\"y\", 2) ])),\n]);\nvar arr = JsonArray.Create(1, 2, 3);\n// (the collection-initializer form `new JsonObject { [\"name\"] = \"Alice\" }` compiles too, but the\n// factories read identically in their mutable and ReadOnly forms, so prefer them)\n\n// read-only directly (good for cached/shared constants): the ReadOnly twin, same call shape\nvar ro = JsonObject.ReadOnly.Create([\n    (\"name\", \"Alice\"),\n    (\"age\", 30),\n    (\"tags\", JsonArray.ReadOnly.Create([\"admin\", \"user\"])),\n]);\n\n// from a CLR value (POCO, collection, primitive)\nJsonValue v   = JsonValue.FromValue(myPoco);              // mutable\nJsonValue rov = JsonValue.ReadOnly.FromValue(myPoco);     // read-only\n\nobj.ToReadOnly();   // freeze for caching\nro.ToMutable();     // get a mutable copy to edit\n</code></pre>\n<hr>\n<h2>3. Reading and navigating</h2>\n<p>Indexers <strong>never throw</strong> on a missing key/index - they return <code>JsonNull.Missing</code> (or <code>JsonNull.Error</code>), so you can chain\nsafely:</p>\n<pre><code>JsonValue city = obj[\"user\"][\"address\"][\"city\"];   // Missing if any hop is absent; no NRE\nbool present   = !obj[\"user\"].IsNullOrMissing();\n</code></pre>\n<p><strong>Read + convert in one step</strong> (the everyday API):</p>\n<pre><code>// Get&lt;T&gt;: optional with default, or required (throws JsonBindingException if null/missing/incompatible)\nint    age   = obj.Get&lt;int&gt;(\"age\", 0);          // default if absent\nstring name  = obj.Get&lt;string&gt;(\"name\");         // throws if absent/null\nGuid   id    = obj.Get&lt;Guid&gt;(\"id\");\n\n// TryGet\nif (obj.TryGet&lt;string&gt;(\"email\", out var email)) { /* ... */ }\n\n// typed children\nJsonObject child = obj.GetObjectOrEmpty(\"meta\");   // never null; empty read-only object if absent\nJsonArray  items = obj.GetArray(\"items\");          // throws if not an array\nif (obj.TryGetObject(\"meta\", out var meta)) { /* ... */ }\n\n// arrays\nint count = items.Count;\nstring first = items.Get&lt;string&gt;(0);\nforeach (var item in items) { /* JsonValue */ }\nforeach (var o in items.AsObjects()) { /* JsonObject items only */ }\n</code></pre>\n<p><strong>Convert a <code>JsonValue</code> to a CLR type</strong> (when you already hold the value):</p>\n<pre><code>string? s = jv.As&lt;string&gt;();          // default(T) (null) if the value is null/missing\nint     n = jv.As&lt;int&gt;(-1);           // custom default if null/missing\nstring  r = jv.Required&lt;string&gt;();    // throws if null/missing\n</code></pre>\n<p><code>As&lt;T&gt;</code> / <code>Get&lt;T&gt;</code> support primitives, <code>Guid</code>/<code>Uuid*</code>, <code>DateTime</code>/<code>DateTimeOffset</code>/<code>DateOnly</code>/<code>TimeSpan</code>,\nNodaTime <code>Instant</code>/<code>Duration</code>, <code>Uri</code>, <code>byte[]</code>/<code>Slice</code>, arrays/<code>List&lt;T&gt;</code>, and your POCOs. Numbers/dates use\n<strong>InvariantCulture</strong>.</p>\n<hr>\n<h2>4. CrystalJson: serialize / parse / deserialize</h2>\n<pre><code>using SnowBank.Data.Json;\n\n// SERIALIZE a CLR value -&gt; JSON\nstring json   = CrystalJson.Serialize(value);                          // formatted, single line\nstring compact= CrystalJson.Serialize(value, CrystalJsonSettings.JsonCompact);\nstring pretty = CrystalJson.Serialize(value, CrystalJsonSettings.JsonIndented);\nSlice  bytes  = CrystalJson.ToSlice(value, CrystalJsonSettings.JsonCompact);   // UTF-8\nbyte[] raw    = CrystalJson.ToBytes(value);\nCrystalJson.SerializeTo(textWriterOrStream, value);                    // streaming\n\n// PARSE text/bytes -&gt; DOM: parse through the DOM types, not through CrystalJson.*\nJsonValue  any = JsonValue.Parse(json);      // string, Slice, ReadOnlySpan&lt;char/byte&gt;\nJsonObject o   = JsonObject.Parse(json);     // throws if it is not an object\nJsonArray  a   = JsonArray.Parse(json);      // throws if it is not an array\n// READ-ONLY (cache-safe) twin of each: the nested ReadOnly class, same entry points\nJsonValue roDom = JsonValue.ReadOnly.Parse(json);   // also JsonObject.ReadOnly.Parse, etc.\n\n// DESERIALIZE text/bytes -&gt; POCO (parse + bind)\nBook book  = CrystalJson.Deserialize&lt;Book&gt;(json);                      // throws if the JSON is null\nBook? maybe= CrystalJson.Deserialize&lt;Book&gt;(json, defaultValue: null);  // null instead of throwing\n\n// Serialize a JsonValue back to text/bytes\nstring s2 = value.ToJsonText();                  // or ToJsonText(settings)\nSlice  b2 = value.ToJsonSlice(CrystalJsonSettings.JsonCompact);\n</code></pre>\n<p><strong>Parse (DOM) vs Deserialize (POCO):</strong> <code>Parse</code> returns a <code>JsonValue</code> tree you navigate; <code>Deserialize&lt;T&gt;</code> binds straight\nto your type. A <code>null</code>/empty/missing input deserializes to <code>null</code> -&gt; throws for a non-nullable <code>T</code> unless you pass a\n<code>defaultValue</code>.</p>\n<p>The intended split: <strong><code>CrystalJson.*</code> serves the POCO route</strong> (<code>Serialize</code>, <code>Deserialize</code>, <code>ToSlice</code>), <strong>the DOM\nparses through the DOM types</strong> (<code>JsonValue.Parse</code>, <code>JsonObject.Parse</code>, <code>JsonArray.Parse</code>, each a <code>new static</code>\nreturning the derived type, throwing when the payload has another shape). Pick <code>JsonObject.Parse</code> when a non-object\npayload is a bug (let it throw); pick <code>JsonValue.Parse</code> plus a type test when it is an ordinary case to handle.\n(<code>CrystalJsonDomWriter.ParseObject(value)</code> is unrelated: it goes the other way, CLR value -&gt; DOM.)</p>\n<h3>CrystalJsonSettings</h3>\n<p>Settings are <strong>immutable and cached</strong>; start from a preset and compose with fluent methods.</p>\n<p>Presets: <code>CrystalJsonSettings.Json</code> (default), <code>.JsonCompact</code>, <code>.JsonIndented</code>, <code>.JsonReadOnly</code> (parse a read-only DOM),\n<code>.JsonStrict</code>, <code>.JsonIgnoreCase</code> (case-insensitive field matching), and <code>JavaScript*</code> variants.</p>\n<p>Common fluent options (chainable, e.g. <code>CrystalJsonSettings.Json.Compacted().CamelCased()</code>):</p>\n<ul>\n<li>Layout: <code>.Compacted()</code>, <code>.Indented()</code>, <code>.Formatted()</code></li>\n<li>Naming: <code>.CamelCased()</code>, <code>.PascalCased()</code></li>\n<li>Nulls/defaults: <code>.WithoutNullMembers()</code> (default), <code>.WithNullMembers()</code>, <code>.WithoutDefaultValues()</code></li>\n<li>Enums: <code>.WithEnumAsStrings()</code> (<strong>the default since 7.4.3</strong>), <code>.WithEnumAsNumbers()</code> - see <em>Enums in the output</em> in section 9 for\nwhat changed and the recipes that restore numbers</li>\n<li>Dates: <code>.WithIso8601Dates()</code> (default), <code>.WithMicrosoftDates()</code> (emits <code>\"\\/Date(ms)\\/\"</code>; <strong>reading</strong> that legacy\nformat always works, with or without this setting)</li>\n<li>Durations: <code>.WithNumericDurations()</code> (default: <code>TimeSpan</code> as a number of seconds), <code>.WithIso8601Durations()</code>\n(emits the legacy <code>\"P1DT2H3M4.005S\"</code> duration string; <strong>reading</strong> both forms always works) <em>(7.4.3+)</em></li>\n<li>Dictionaries: <code>.WithDictionariesAsMaps()</code> (default, <code>{\"k\":v}</code>), <code>.WithDictionariesAsPairArrays()</code> (emits the legacy\n<code>[{\"Key\":k,\"Value\":v}]</code> shape; again, <strong>reading</strong> both shapes always works) <em>(7.4.3+)</em></li>\n<li>Read-only result: <code>.AsReadOnly()</code></li>\n</ul>\n<p><strong>Parsing leniency</strong> (deserialization only; none of these change what you emit). The parser is deliberately\npermissive by default, which is wrong for untrusted input:</p>\n<table>\n<thead>\n<tr>\n<th>Option</th>\n<th>Default</th>\n<th>Tighten with</th>\n<th>Loosen with</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>JavaScript comments (<code>// ...</code>, <code>/* ... */</code>)</td>\n<td>accepted</td>\n<td><code>.WithoutComments()</code></td>\n<td><code>.WithComments()</code></td>\n</tr>\n<tr>\n<td>trailing commas (<code>[1, 2, ]</code>)</td>\n<td>accepted</td>\n<td><code>.WithoutTrailingCommas()</code></td>\n<td><code>.WithTrailingCommas()</code></td>\n</tr>\n<tr>\n<td>content after the top-level value</td>\n<td>rejected</td>\n<td><code>.WithoutTrailingData()</code></td>\n<td><code>.WithTrailingData()</code></td>\n</tr>\n<tr>\n<td>duplicate field names</td>\n<td>last one wins</td>\n<td><code>.ThrowOnDuplicateFields()</code></td>\n<td><code>.FlattenDuplicateFields()</code></td>\n</tr>\n</tbody>\n</table>\n<p>⚠️ The <strong>property</strong> is <code>settings.AllowTrailingData</code>; the fluent <strong>method</strong> that sets it is <code>.WithTrailingData()</code>.\nThere is no <code>.AllowTrailingData()</code> method. Same shape for the others: read a <code>bool</code> property, set it with a\n<code>With*</code> / <code>Without*</code> method.</p>\n<p><code>CrystalJsonSettings.JsonStrict</code> is the shorthand for the first two rows (no comments, no trailing commas). It\ndoes <strong>not</strong> touch duplicate fields, so add <code>.ThrowOnDuplicateFields()</code> yourself if a repeated key must be an\nerror rather than a silent overwrite.</p>\n<p>To read several consecutive documents out of one buffer, use <code>CrystalJson.ParseFragment</code> or the streaming\nreader instead of <code>.WithTrailingData()</code>, which parses the first value and silently drops the rest.</p>\n<hr>\n<h2>5. The source generator (your domain types)</h2>\n<p>For POCOs, prefer the generator over the DOM: it emits a fast, reflection-free, AOT-friendly converter <strong>and</strong> typed\nread-only/writable proxies. (This is how the document-collection layers built on this stack store their documents.)</p>\n<h3>Declare</h3>\n<p>Put <code>[CrystalSerializable(typeof(T))]</code> (one per root type) on a <code>public static partial class</code> marked\n<code>[CrystalJsonConverter]</code>. Nested types are discovered automatically. Use <code>[JsonProperty(\"name\")]</code> to rename a field.</p>\n<pre><code>using SnowBank.Data.Json;\n\npublic sealed record Book\n{\n    [JsonProperty(\"id\")]\n    public required string Id { get; init; }\n\n    [JsonProperty(\"title\")]\n    public required string Title { get; init; }\n\n    [JsonProperty(\"year\")]\n    public int Year { get; init; }\n    public Author? Author { get; init; }   // nested type: auto-discovered\n}\n\n[CrystalJsonConverter]                       // or [CrystalJsonConverter(CrystalJsonSerializerDefaults.Web)] for camelCase + ignore-case\n[CrystalSerializable(typeof(Book))]\npublic static partial class AcmeSerializers { }       // generated members land here\n</code></pre>\n<h4>The container vocabulary <em>(7.4.4+)</em></h4>\n<p><code>[CrystalJsonConverter]</code> is a <strong>mono-format alias</strong>: it means \"this class hosts generated code\" <strong>plus</strong>\n\"produce the JSON format, with these parameters\". The two halves also exist separately, which is what a\ncontainer producing several formats needs:</p>\n<table>\n<thead>\n<tr>\n<th>Attribute</th>\n<th>Namespace</th>\n<th>Role</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td><code>[CrystalConverter]</code></td>\n<td><code>SnowBank.Data</code></td>\n<td>the container marker; says nothing about the formats</td>\n</tr>\n<tr>\n<td><code>[CrystalSerializable(typeof(T))]</code></td>\n<td><code>SnowBank.Data</code></td>\n<td>registers a root type; repeatable; feeds every output format</td>\n</tr>\n<tr>\n<td><code>[CrystalJsonOutput(...)]</code></td>\n<td><code>SnowBank.Data.Json</code></td>\n<td>requests the JSON format (profile, naming policy, case-insensitivity)</td>\n</tr>\n<tr>\n<td><code>[CrystalXmlOutput(...)]</code></td>\n<td><code>SnowBank.Data.Xml</code></td>\n<td>requests the XML format (see <code>Documentation/CrystalXml.md</code>)</td>\n</tr>\n<tr>\n<td><code>[CrystalJsonConverter(...)]</code></td>\n<td><code>SnowBank.Data.Json</code></td>\n<td>alias: <code>[CrystalConverter]</code> + <code>[CrystalJsonOutput]</code>, JSON only</td>\n</tr>\n<tr>\n<td><code>[CrystalXmlConverter(...)]</code></td>\n<td><code>SnowBank.Data.Xml</code></td>\n<td>alias: <code>[CrystalConverter]</code> + <code>[CrystalXmlOutput]</code>, XML only</td>\n</tr>\n</tbody>\n</table>\n<p>Rules the compiler enforces: a <code>[CrystalConverter]</code> naming no output format is refused (<code>CRYS0001</code>);\na mono-format alias next to an output attribute is refused (<code>CRYS0002</code> - use <code>[CrystalConverter]</code> with\nexplicit output attributes instead); several container markers on one class are refused (<code>CRYS0003</code>).</p>\n<pre><code>// a container that produces BOTH formats from one set of registered types\n[CrystalConverter]\n[CrystalJsonOutput(CrystalJsonSerializerDefaults.Web)]\n[CrystalXmlOutput]\n[CrystalSerializable(typeof(Book))]\npublic static partial class CatalogSerializers { }\n</code></pre>\n<p><code>[CrystalJsonSerializable(typeof(T))]</code> is the former spelling of <code>[CrystalSerializable]</code>: still working\nand byte-identical, but <code>[Obsolete]</code> (registration never was JSON-specific).</p>\n<h3>Self-serializable types: the entity IS its own container <em>(7.4.3+)</em></h3>\n<p>The container above (<code>AcmeSerializers</code>) is one way to register a type. The other is to let the type carry its own\ngenerated code, which is what you want when a <strong>layer</strong> owns a vocabulary and should not force every consuming\napplication to also declare a JSON container.</p>\n<p><code>[CrystalJsonSelfSerializable]</code> is a <strong>meta-attribute</strong>: you put it on one of <em>your own</em> attribute classes, and\nevery type decorated with that attribute is opted into generation.</p>\n<pre><code>// the layer declares its vocabulary ONCE\n[CrystalJsonSelfSerializable]\n[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct)]\npublic sealed class MyEntityAttribute : Attribute { }\n\n// the application just declares an entity - no container, no [CrystalSerializable]\n[MyEntity]\npublic sealed partial record Widget\n{\n    public required string Name { get; init; }\n    public Author? Author { get; init; }      // referenced types are still picked up\n}\n</code></pre>\n<p>Everything generated lands inside <strong>one</strong> nested static class named <code>Json</code>, so the entity reserves exactly one\nmember name:</p>\n<pre><code>Widget.Json.Default          // the converter (the container mode's AcmeSerializers.Widget)\nWidget.Json.ReadOnly         // read-only proxy\nWidget.Json.Writable         // writable proxy\nWidget.Json.PropertyNames    // property-name constants\nWidget.Json.GetResolver()    // the per-container resolver, same as the container mode\nWidget.Json.ToJsonText(w)    // the static helpers live there too\n</code></pre>\n<p>Referenced types nest inside that same scope under their plain names: <code>Author</code>'s converter is\n<code>Widget.Json.Author.Default</code>. Inside the scope they cannot shadow the referenced type in the entity's own\nsource, which is what the single reserved name buys.</p>\n<p>The one-name rule is the design, not an implementation detail: a future generator for another format claims a\nsibling scope (<code>Widget.Cbor</code>) without renegotiating anything. It also means the <code>Json</code> scope is entirely\ngenerated code, so it carries the generated-code attributes (<code>GeneratedCode</code>, <code>DebuggerNonUserCode</code>,\n<code>ExcludeFromCodeCoverage</code>, <code>DynamicallyAccessedMembers</code>) that could not be put on the entity partial, since\nthat partial is your source.</p>\n<p>This is how a document-collection attribute works in a layer built on this stack: the application writes one\nattribute on the entity, and the JSON converter, both proxies and the layer's own generated schema all fall\nout of it.</p>\n<p>Things to know before you use it:</p>\n<ul>\n<li>The entity must be <strong><code>partial</code>, non-generic, and not nested</strong>. The generator rejects the others with\n<code>CJSON0004</code> / <code>CJSON0005</code>.</li>\n<li><strong>Your entity may not declare a member named <code>Json</code>.</strong> That is <code>CJSON0006</code>, an error, reported at the entity\ndeclaration in your own source. The message carries the remedies: rename the member and keep its serialized name\nwith <code>[JsonProperty(\"json\")]</code>, or move the type to a <code>[CrystalJsonConverter]</code> container instead.</li>\n<li><strong>A referenced type named like a scope member</strong> (<code>Default</code>, <code>ReadOnly</code>, <code>Writable</code>, <code>PropertyNames</code>, …) is\n<code>CJSON0007</code>, a warning. That type is excluded from generation and falls back to runtime serialization, so it\nstill works, just without a generated converter.</li>\n<li>Hint names are namespace-qualified in this mode, because entity names collide across namespaces far more\noften than container names do.</li>\n<li>The <code>[CrystalJsonConverter]</code> + <code>[CrystalSerializable]</code> container path is untouched and still correct.\nPrefer the container when you register third-party types you cannot annotate, or a set of unrelated\ntypes; prefer self mode when the type is yours and a layer already marks it.</li>\n</ul>\n<h3>csproj wiring (the part most often gotten wrong)</h3>\n<p>Reference the generator project/package <strong>as an analyzer</strong>, and ensure C# 9+:</p>\n<pre><code>&lt;PropertyGroup&gt;\n  &lt;LangVersion&gt;latest&lt;/LangVersion&gt;\n&lt;/PropertyGroup&gt;\n&lt;ItemGroup&gt;\n  &lt;ProjectReference Include=\"path/to/SnowBank.Serialization.Json.CodeGen.csproj\"\n                    OutputItemType=\"Analyzer\" ReferenceOutputAssembly=\"false\" /&gt;\n&lt;/ItemGroup&gt;\n</code></pre>\n<p>(If consuming via NuGet, the analyzer ships with <code>SnowBank.Core</code> / its codegen package.)</p>\n<p><strong>The language floor is C# 9, and the generator checks it explicitly</strong>: below C# 9 it reports <code>SYSLIB1221</code>\n(\"language version not supported by the source generator\") and generates nothing. <code>latest</code> clears the gate with\nmargin, but the actual requirement is only <code>&gt;= 9</code> — the classic trigger is a ported legacy project still pinning\na netfx-era <code>&lt;LangVersion&gt;7.3&lt;/LangVersion&gt;</code>. No other project setting is required: the generated files fully\nqualify every name (they work without <code>ImplicitUsings</code>) and are warning-free under <code>#nullable enable</code>, including\nfor members declared in nullable-oblivious code.</p>\n<h3>Use</h3>\n<pre><code>// POCO &lt;-&gt; JSON text\nstring json = AcmeSerializers.Book.ToJsonText(book);\nBook   back = AcmeSerializers.Book.Deserialize(json);\n\n// POCO &lt;-&gt; JsonValue (DOM)\nJsonValue packed = AcmeSerializers.Book.Pack(book);\nBook      from   = AcmeSerializers.Book.Unpack(jsonObject);\n\n// runtime resolver (pass to CrystalJson APIs and to layers that must resolve your converters)\nICrystalJsonTypeResolver resolver = AcmeSerializers.GetResolver();\n</code></pre>\n<h3>Read-only / writable proxies (zero-copy typed views over the DOM)</h3>\n<pre><code>AcmeSerializers.Book.ReadOnly ro = AcmeSerializers.Book.ToReadOnly(book);   // typed read-only view over a JsonValue\nstring title = ro.Title;                                  // typed property read\nJsonValue dom = ro.ToJsonValue();                         // underlying (read-only) JsonValue\nBook poco = ro.ToValue();                                 // materialize the POCO\n\n// edit via copy-on-write: the original proxy is unchanged, you get a new frozen proxy\nAcmeSerializers.Book.ReadOnly edited = ro.With(m =&gt; { m.Year = 2025; });\n\n// or an explicit mutable proxy\nAcmeSerializers.Book.Writable w = ro.ToMutable();\nw.Year = 2025;\n</code></pre>\n<p>Absence propagates through a proxy the way it does through the DOM: a chain across a missing inner object keeps\nnavigating (<code>proxy.Metadata.IsNullOrMissing()</code> tells you), an optional member reads as its default, and a\n<code>required</code> member absent from the document throws <code>JsonBindingException</code>, never a <code>NullReferenceException</code>\n(pinned by <code>Test_JsonReadOnlyProxy_With_Empty_Object</code> in <code>SnowBank.Serialization.Json.CodeGen.Tests</code>).</p>\n<p><em>(7.4.5+)</em> A type that decides its own format (IJson* interfaces, or a container hook, section 7) gets NO\ngenerated proxies, with a <code>CJSON0025</code> warning: the generator cannot describe a shape it does not produce.</p>\n<p>Note: <code>.With(...)</code> (copy-on-write edit) is a method on the GENERATED typed proxies shown here, not on a raw DOM\n<code>JsonObject</code>/<code>JsonArray</code>. For a plain DOM value there is no <code>.With(...)</code>: freeze with <code>value.ToReadOnly()</code> and edit a\ncopy with <code>value.ToMutable()</code> (section 2), then set fields via the indexer.</p>\n<hr>\n<h2>6. Mutating JSON: MutableJsonValue (and ObservableJsonValue)</h2>\n<p><code>MutableJsonValue</code> is a mutation proxy used inside \"write\" closures (document updates in a collection layer, the <code>doc.Write(root =&gt; ...)</code> closures of a reactive layer).\n<code>ObservableJsonValue</code> is the read side that tracks which fields were read (for reactive views). You usually interact via\nthe <code>root</code> handed to a write callback:</p>\n<pre><code>doc.Write(root =&gt;\n{\n    root[\"status\"].Set(\"online\");                 // set a scalar field\n    root.Set(\"count\", 42);                         // typed set (auto-converts the CLR value)\n    root[\"point\"][\"x\"].Set(123);                   // nested set (intermediate objects auto-created via GetOrCreateObject)\n    root.Set(JsonPath.Create(\"a.b[0]\"), \"deep\");   // path-based set\n    root[\"items\"].Add(\"newItem\");                  // APPEND to the array at root[\"items\"]\n});\n</code></pre>\n<p><strong>Footgun - <code>Add</code> means different things on objects vs arrays:</strong></p>\n<ul>\n<li><code>root.Add(\"field\", value)</code> adds a <strong>field</strong> to the object (throws if the field already exists).</li>\n<li><code>root[\"field\"].Add(value)</code> <strong>appends</strong> to the array at <code>root[\"field\"]</code>.</li>\n</ul>\n<p>They are not interchangeable. Re-creating an existing field with <code>Add</code> throws; to append, index into the array first.</p>\n<p><strong>Don't hold a child proxy across a parent mutation</strong> - it goes stale. Re-get it, or do it in one chain:</p>\n<pre><code>// stale:\nvar s = root[\"settings\"]; root[\"settings\"].Set(newSettings); s[\"k\"].Set(v);   // BUG: s is stale\n// good:\nroot[\"settings\"][\"k\"].Set(v);\n</code></pre>\n<hr>\n<h2>7. Custom (de)serialization: the IJson* interfaces</h2>\n<p>When the generator can't cover a type (e.g. a hand-tuned encoding), implement these directly:</p>\n<pre><code>public interface IJsonSerializable          { void JsonSerialize(CrystalJsonWriter writer); }\npublic interface IJsonPackable              { JsonValue JsonPack(CrystalJsonSettings settings, ICrystalJsonTypeResolver resolver); }\npublic interface IJsonDeserializable&lt;TSelf&gt; { static abstract TSelf JsonDeserialize(JsonValue value, ICrystalJsonTypeResolver? resolver); }\n</code></pre>\n<p>By convention the concrete <code>JsonDeserialize</code> implementation declares the resolver with a default (<code>ICrystalJsonTypeResolver? resolver = null</code>)\nso callers can omit it; that still satisfies the interface. <code>JsonPack</code> (to DOM) and <code>JsonDeserialize</code> (from DOM) must be inverses - round-trip them in a test. Build values with\n<code>JsonString.Return(...)</code>, <code>JsonNumber.Return(...)</code>, <code>JsonArray.ReadOnly.Create(...)</code>. Handle null/missing defensively in\n<code>JsonDeserialize</code>. (Example in the wild: a compact id type packed as a <code>JsonArray</code> of its parts.)</p>\n<h3>Generated converters call a registered type's own IJson* implementations <em>(7.4.5+)</em></h3>\n<p>For a type that implements one of the three interfaces AND is registered with a <code>[CrystalConverter]</code>\ncontainer, the generated converter calls the type's own method for each interface it implements, and\ngenerates the remaining methods from the members. Before 7.4.5 the generated converter ignored the\ninterfaces and built the output from the members, so the generated and reflection paths produced\ndifferent output for the same type. The type's format takes precedence over the container's profile\nsettings.</p>\n<p>To force the old member-based output for one type, opt it out where it is registered:</p>\n<pre><code>[CrystalSerializable(typeof(LegacyRecord), IgnoreCustomSerialization = true)]\n</code></pre>\n<p>Two limits: the opt-out cannot help a type the generator cannot construct from members (<code>required</code>\nmembers with no parameterless constructor), and it cannot be applied to a type discovered through\nanother type (a type reached through another type's member is registered automatically, and no\nattribute can be applied to it).</p>\n<h3>Overriding a generated converter with a hand-written method <em>(7.4.5+)</em></h3>\n<p>The per-type scope a container generates is <code>partial</code>. An author can declare a <code>Serialize</code>, <code>Pack</code>, or\n<code>Unpack</code> method in their own part, and the generated converter routes that facet to it while keeping\nthe <code>IJsonConverter&lt;T&gt;</code> implementation, the null check, the circular-reference check, and the\nread-only conversion. The null check runs BEFORE the author's method: a null instance serializes as\nJSON null and the method is never called with one, so it takes a non-nullable parameter and needs no\nnull branch.\nThis override is per container, and takes precedence over the type's own IJson* methods, so two\ncontainers can serialize one type differently. A scope is named after the type it serves, so inside the container\nthat name refers to the SCOPE: qualify the serialized type in the registration and the hook signatures.</p>\n<pre><code>[CrystalConverter]\n[CrystalJsonOutput]\n[CrystalSerializable(typeof(Telemetry.SensorReading))]\npublic static partial class TelemetrySerializers\n{\n\tpublic static partial class SensorReading\n\t{\n\t\t// replaces the generated Pack body for this container only; the generated code\n\t\t// handles a null instance before this method runs, so there is no null case here\n\t\tpublic static JsonValue Pack(Telemetry.SensorReading instance, CrystalJsonSettings? settings = default, ICrystalJsonTypeResolver? resolver = default)\n\t\t\t=&gt; JsonArray.Create(JsonString.Return(instance.Sensor), JsonNumber.Return(instance.Value));\n\t}\n}\n</code></pre>\n<p>The names <code>Serialize</code>, <code>Pack</code>, and <code>Unpack</code> are reserved inside a generated scope: one of them with an\nincompatible signature is a hard error (<code>CJSON0024</code>) naming the expected shape, never a silent fallback.\nFor a hooked polymorphic type, the generator does not write the type discriminator: the hook must\nwrite it itself (the constants <code>PropertyNames._TypeDiscriminatorProperty_</code> /\n<code>PropertyEncodedNames._TypeDiscriminatorValue_</code> are public in the scope for that purpose).</p>\n<h3>Member converters: converting ONE member, not the whole type <em>(7.4.3+)</em></h3>\n<p>The interfaces above take over an entire type. When you only need to change how <strong>one member</strong> is written, attach the\nbehaviour to that member instead - and <strong>reach for a built-in attribute before writing any code.</strong></p>\n<h3>Start here: the built-in, <code>[JsonBooleanLiterals]</code></h3>\n<p>Booleans written as <code>\"0\"</code>/<code>\"1\"</code> (or <code>0</code>/<code>1</code>) are the common legacy case, and there is nothing to implement:</p>\n<pre><code>[JsonBooleanLiterals(\"0\", \"1\")]                          // strings; tolerant read\n[JsonBooleanLiterals(\"0\", \"1\", StrictLiterals = true)]   // rejects genuine true/false\n[JsonBooleanLiterals(0, 1)]                              // numbers\n[JsonBooleanLiterals(null, \"1\")]                         // true -&gt; \"1\", false -&gt; member ABSENT\n[JsonBooleanLiterals(null, true)]                        // true -&gt; true, false -&gt; member ABSENT\npublic bool Enabled { get; set; }\n</code></pre>\n<p>A <strong>null</strong> first argument means the member is <strong>not emitted at all</strong> when the value is false, for a consumer that\nexpects either the member absent or the true literal. <code>[JsonBooleanLiterals(null, true)]</code> is the idiom for\n\"emit true, or emit nothing\": the output stays ordinary JSON booleans and the only thing the attribute changes is\nthe omission, which says the intent in C# better than a condition whose \"default\" the reader has to decode as\nfalse. It is exactly equivalent to <code>[JsonBooleanLiterals(\"0\",\"1\")]</code> plus\n<code>[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]</code> (pinned byte-identical by a test), and\n<code>[JsonIgnore(Condition = ...)]</code> remains the general mechanism for every other member type. <code>[JsonBooleanLiterals(false, true)]</code>\nis legal and does nothing: both literals are what a <code>bool</code> serializes to anyway.</p>\n<p>Arguments accept a <strong>string, a bool, or a numeric value</strong>, and the two do not have to match\n(<code>[JsonBooleanLiterals(\"0\", 1)]</code> is legal, because legacy formats are not always consistent). Anything else is\nrefused: the reflection path throws when the contract is built, the generator reports <strong><code>CJSON0017</code></strong>, same\nmessage. The parameters are typed <code>object</code> so that <code>null</code> can carry the omit meaning, which is why that check\nexists at all: it replaces the compiler check the old typed constructors gave you.</p>\n<p>With no false literal, a present JSON <code>false</code> reads as <strong>false even under <code>StrictLiterals</code></strong>: absence already\nmeans false in that shape, so an explicit <code>false</code> is the same state spelled out. Strict still rejects anything\nthat is not a configured literal. That combination is incoherent though, so the generator warns (<code>CJSON0018</code>).</p>\n<p><strong>Why that one is generator-only, when the other diagnostics exist on both paths:</strong> <code>CJSON0015</code> and <code>CJSON0016</code>\nrefuse constructs that would otherwise <strong>behave differently</strong> on the two paths, so they have to exist on both, and\nthe reflection path throws the identical message at contract build. <code>CJSON0018</code> changes no behaviour at all: it is\nadvice about a pointless combination, and a compile-time nudge is the whole feature. There is no sensible moment\nto emit a warning during contract build, and throwing would be wildly out of proportion.</p>\n<p>Reads are tolerant by default (the configured literals, case-insensitively, <strong>and</strong> genuine <code>true</code>/<code>false</code>), so a\nmodernized producer needs no redeploy; an unknown literal is a <code>JsonBindingException</code>, never a silent <code>false</code>. Applying\nit to a non-boolean member fails loudly (reflection: at metadata build; generator: error <code>CJSON0009</code>).</p>\n<h3>When no built-in covers it: a member converter</h3>\n<p>For anything else (a domain scalar as a string, a packed identifier), write a converter. Recognition is <strong>per facet</strong>: a\nconverter is honored for whichever of <code>IJsonPacker&lt;T&gt;</code> (writing) and <code>IJsonDeserializer&lt;T&gt;</code> (reading) it implements, so\na write-only or read-only type implements one side. <code>IJsonMemberConverter&lt;T&gt;</code> is the convenience bundle for the\nsymmetric case, never a requirement:</p>\n<pre><code>public interface IJsonMemberConverter&lt;T&gt; : IJsonPacker&lt;T&gt;, IJsonDeserializer&lt;T&gt; { }   // zero new members\n\n// shown on a bool purely because it is the shortest possible body -\n// for THIS behaviour use [JsonBooleanLiterals] above and write no converter at all\npublic sealed class BoolAsBitStringConverter : IJsonMemberConverter&lt;bool&gt;\n{\n    public JsonValue Pack(bool v, CrystalJsonSettings? s = null, ICrystalJsonTypeResolver? r = null) =&gt; JsonString.Return(v ? \"1\" : \"0\");\n    public bool Unpack(JsonValue v, ICrystalJsonTypeResolver? r) =&gt; /* tolerant read */;\n}\n\n[JsonConvertWith(typeof(BoolAsBitStringConverter))]   // CrystalJson's own attribute - preferred\npublic bool Enabled { get; set; }                     // output: \"1\" / \"0\", both paths, both directions\n</code></pre>\n<p>Converters never see <code>null</code>: null and missing are handled before the converter runs (and a converter written for <code>T</code>\nlifts over a <code>T?</code> member for free). Using the <strong>missing</strong> direction fails loudly, naming the facet to add - there is no\nsilent fallback to the default path. A source-generated <code>IJsonConverter&lt;T&gt;</code> implements both parents, so a generated\nwhole-type converter can be named on a member with no adapter.</p>\n<p><strong>Nullable members</strong> <em>(7.4.3+)</em>: a converter may be declared for the nullable form itself\n(<code>IJsonMemberConverter&lt;DateTime?&gt;</code> on a <code>DateTime?</code> member). The probe order is <strong>exact form first, then the lift</strong>, on\nboth paths, so a <code>T?</code> declaration takes over every <strong>present</strong> value and can answer \"no value\" for a\npresent-but-unreadable input (<code>\"\"</code>, an unparseable token) - distinctly from <code>default(T)</code>, which stays a real value, and\nfrom JSON null/missing, which stay the pipeline's on both sides. The <code>T?</code> declaration transfers the <strong>read side only</strong>:\n<code>Pack</code> still never sees null, and the null-member format follows the settings (<code>WithNullMembers()</code> etc.), so <em>a member\nconverter cannot represent absence for a nullable member whose absent form is not JSON null, unless it is declared for\nthe nullable type itself - and even then only when reading</em>. A <code>T?</code> converter named on a NON-nullable member is refused\nloudly (reflection: at metadata build; generator: <code>CJSON0010</code>).</p>\n<p><strong>Three spellings, in precedence order</strong> - all feed the same per-member slot, honored by the reflection path <em>and</em> the\ngenerator (including the generated proxies). Precedence is the order the runtime resolves them, not a recommendation:\nprefer a built-in when one fits, then <code>[JsonConvertWith]</code>.</p>\n<table>\n<thead>\n<tr>\n<th>Spelling</th>\n<th>When to use it</th>\n<th>Names a type with neither facet</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td><code>[JsonConvertWith(typeof(X))]</code></td>\n<td>your own converter; CrystalJson's own attribute, which System.Text.Json never inspects</td>\n<td><strong>fails loudly</strong> (reflection: on metadata build; generator: error <code>CJSON0010</code>)</td>\n</tr>\n<tr>\n<td><code>[JsonBooleanLiterals(\"0\", \"1\")]</code></td>\n<td><strong>prefer this for booleans</strong> - built in, no converter to write</td>\n<td>n/a</td>\n</tr>\n<tr>\n<td>STJ / Newtonsoft <code>[JsonConverter(typeof(X))]</code></td>\n<td>only when the named type is a <strong>real dual-shape converter</strong> both serializers can execute</td>\n<td><strong>silently ignored</strong> (keeps a half-migrated DTO serializable; starts working once <code>X</code> gains a facet)</td>\n</tr>\n</tbody>\n</table>\n<p>Both spellings also work <strong>on a type</strong>, covering standalone values, DTO members and collection elements on all paths; a\ntype-level converter wins over the duck-typed <code>JsonSerialize</code>/<code>JsonPack</code> methods and the <code>IJson*</code> interfaces.</p>\n<h3>Generator diagnostics</h3>\n<table>\n<thead>\n<tr>\n<th>Id</th>\n<th>Level</th>\n<th>Meaning</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td><code>CJSON0004</code> / <code>CJSON0005</code></td>\n<td>error</td>\n<td>self-serializable entity is generic, nested, or not <code>partial</code> (section 5)</td>\n</tr>\n<tr>\n<td><code>CJSON0006</code></td>\n<td>error</td>\n<td>the entity declares a member named <code>Json</code>, colliding with the generated scope (section 5)</td>\n</tr>\n<tr>\n<td><code>CJSON0007</code></td>\n<td>warning</td>\n<td>a referenced type is named like a scope member; excluded from generation, falls back to runtime</td>\n</tr>\n<tr>\n<td><code>CJSON0008</code></td>\n<td><strong>error</strong></td>\n<td>an unconditional <code>[JsonIgnore]</code> on a member that also carries <code>[DataMember]</code>, <code>[JsonInclude]</code> or <code>[JsonProperty]</code>: a dual-output DTO is not supported - split it, one DTO per serializer (the reflection path throws the same refusal at contract build). The <code>[IgnoreDataMember]</code> sibling shape stays a warning</td>\n</tr>\n<tr>\n<td><code>CJSON0009</code></td>\n<td>error</td>\n<td><code>[JsonBooleanLiterals]</code> on a non-boolean member</td>\n</tr>\n<tr>\n<td><code>CJSON0010</code></td>\n<td>error</td>\n<td><code>[JsonConvertWith]</code> names a type implementing neither converter facet</td>\n</tr>\n<tr>\n<td><code>CJSON0012</code></td>\n<td>warning (suppressible)</td>\n<td>an <code>internal</code> member with no include/exclude signal: serialized by generated converters, invisible to reflection; pin the intent with <code>[JsonInclude]</code> or <code>[JsonIgnore]</code></td>\n</tr>\n<tr>\n<td><code>CJSON0015</code></td>\n<td>error</td>\n<td>a serialization callback (<code>[OnSerializing]</code> and friends) declares the legacy <code>StreamingContext</code> parameter; drop it, or replace it with <code>JsonValue</code>/<code>JsonObject</code>/<code>JsonArray</code>. The reflection path throws the same message at contract build</td>\n</tr>\n<tr>\n<td><code>CJSON0016</code></td>\n<td>error</td>\n<td>a type declares <code>[OnDeserializing]</code> alongside a <code>required</code> or <code>init</code>-only member. The pre-populate callback must observe an unpopulated instance, so members are assigned after construction, which neither of those allows; the message names the member and the remedy for its specific construct</td>\n</tr>\n<tr>\n<td><code>CJSON0017</code></td>\n<td>error</td>\n<td>a <code>[JsonBooleanLiterals]</code> argument has a type with no JSON format form; use a string, a bool, or a numeric value. The reflection path throws the same message when the contract is built</td>\n</tr>\n<tr>\n<td><code>CJSON0018</code></td>\n<td>warning (suppressible)</td>\n<td><code>StrictLiterals</code> combined with a null false literal: strict mode enforces the configured literals, and with no false literal there is nothing on the false side to enforce. Generator-only on purpose, because it changes no behaviour (see below)</td>\n</tr>\n<tr>\n<td><code>CJSON0013</code></td>\n<td>error</td>\n<td>a format profile (<code>DataContractCompat</code>) combined with a naming policy (camelCase and friends); use the dual-container pattern instead. <code>PropertyNameCaseInsensitive</code> is NOT a trigger: it is a read-side tolerance for incoming member names and changes nothing about what the profile writes</td>\n</tr>\n<tr>\n<td><code>CJSON0024</code></td>\n<td>error</td>\n<td><em>(7.4.5+)</em> a method named <code>Serialize</code>/<code>Pack</code>/<code>Unpack</code> in a generated per-type scope has an incompatible signature; the message names the expected one. Correct it or rename the method</td>\n</tr>\n<tr>\n<td><code>CJSON0025</code></td>\n<td>warning</td>\n<td><em>(7.4.5+)</em> no <code>ReadOnly</code>/<code>Writable</code> proxy for a type that decides its own format (IJson* interfaces or a container hook): the generator cannot describe a shape it does not produce. The converter itself is unaffected</td>\n</tr>\n<tr>\n<td><code>CJSON0026</code></td>\n<td>error</td>\n<td><em>(7.4.5+)</em> a registration resolves to a static class, usually an unqualified <code>typeof(X)</code> inside a container whose scope shadows the type name; the message names the qualification fix</td>\n</tr>\n</tbody>\n</table>\n<hr>\n<h2>8. JsonPath</h2>\n<p><code>JsonPath</code> addresses a nested location with dot/bracket notation:</p>\n<pre><code>var p = JsonPath.Create(\"user.address.city\");\nvar q = JsonPath.Create(\"items[0]\");\nvar last = JsonPath.Create(^1);     // last item; ^0 is the append position\n\nJsonValue v = obj.GetPathValueOrDefault(p);\nroot.Set(p, \"new value\");           // on a MutableJsonValue\n</code></pre>\n<hr>\n<h2>9. Attributes: what each path honors (and legacy interop)</h2>\n<p>There are <strong>two independent (de)serialization paths, with different attribute vocabularies</strong>. Getting this wrong\nsilently changes the output, so check the matrix before annotating a DTO:</p>\n<ul>\n<li><strong>Reflection</strong> (<code>CrystalJsonTypeResolver</code>) - what <code>CrystalJson.Serialize</code> / <code>Deserialize&lt;T&gt;</code> / <code>JsonValue.FromValue</code>\nuse for a type with no generated converter.</li>\n<li><strong>Source generator</strong> - what <code>[CrystalJsonConverter]</code> + <code>[CrystalSerializable(typeof(T))]</code> emit.</li>\n</ul>\n<table>\n<thead>\n<tr>\n<th>Attribute</th>\n<th>Reflection</th>\n<th>Source generator</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td><code>[JsonProperty(\"x\")]</code> (SnowBank; also <code>DefaultValue</code>, <code>EnumFormat</code>, <code>NumberFormat</code>)</td>\n<td>YES (all four)</td>\n<td>YES (all four) <em>(<code>EnumFormat</code> and <code>NumberFormat</code> since 7.4.3, proxy setters included)</em></td>\n</tr>\n<tr>\n<td><code>[JsonProperty(NumberFormat = JsonNumberFormat.String)]</code> <em>(7.4.3+)</em></td>\n<td>YES - the member's numbers write as strings (the exact numeric literal, decimal scale included; protects 64-bit values from JavaScript precision loss); reads always accept both forms</td>\n<td>YES, all write routes (converter, Pack, proxy setters), byte-parity pinned</td>\n</tr>\n<tr>\n<td>STJ <code>[JsonPropertyName(\"x\")]</code></td>\n<td>YES</td>\n<td>YES</td>\n</tr>\n<tr>\n<td>STJ <code>[JsonIgnore]</code> / <code>[JsonIgnore(Condition = ...)]</code></td>\n<td>YES, full STJ semantics <em>(7.4.3+)</em></td>\n<td>YES, full STJ semantics <em>(7.4.3+)</em></td>\n</tr>\n<tr>\n<td><code>[IgnoreDataMember]</code></td>\n<td>YES <em>(7.4.3+)</em> - excludes the member on a non-<code>[DataContract]</code> type; on a <code>[DataContract]</code> type the <code>[DataMember]</code> opt-in still governs (DCJS's own precedence)</td>\n<td>counts as an ignore signal <em>(7.4.3+)</em></td>\n</tr>\n<tr>\n<td>STJ <code>[JsonInclude]</code> (non-public members/accessors)</td>\n<td>YES <em>(7.4.3+)</em>, a superset of STJ</td>\n<td>YES <em>(7.4.3+)</em> - reached through accessor thunks (<code>[UnsafeAccessor]</code> where the TFM has it, reflection accessors downlevel); <code>SYSLIB1038</code> is retired. An <code>internal</code> member with NO include/exclude signal still diverges (generated-only inclusion, kept for format compatibility) and gets the suppressible warning <code>CJSON0012</code> nudging an explicit <code>[JsonInclude]</code> or <code>[JsonIgnore]</code></td>\n</tr>\n<tr>\n<td>STJ <code>[JsonPolymorphic]</code> + <code>[JsonDerivedType]</code></td>\n<td>YES (discriminator name <strong>and</strong> values are free-form)</td>\n<td>YES</td>\n</tr>\n<tr>\n<td><code>[JsonConvertWith(typeof(X))]</code> (SnowBank), members <strong>and</strong> types</td>\n<td>YES <em>(7.4.3+)</em></td>\n<td>YES <em>(7.4.3+)</em></td>\n</tr>\n<tr>\n<td><code>[JsonBooleanLiterals]</code> (SnowBank)</td>\n<td>YES <em>(7.4.3+)</em></td>\n<td>YES <em>(7.4.3+)</em></td>\n</tr>\n<tr>\n<td>STJ / Newtonsoft <code>[JsonConverter(typeof(X))]</code>, members <strong>and</strong> types</td>\n<td>YES <em>(7.4.3+)</em> when <code>X</code> implements a converter facet; <strong>silently ignored</strong> otherwise (see section 7)</td>\n<td>YES <em>(7.4.3+)</em>, same posture, facet checked at compile time</td>\n</tr>\n<tr>\n<td>Enum custom literals: <code>[JsonStringEnumMemberName]</code> (STJ 9+) / <code>[EnumMember(Value=...)]</code> on enum fields</td>\n<td>YES <em>(7.4.3+)</em>, both directions</td>\n<td>YES <em>(7.4.3+)</em>, both directions</td>\n</tr>\n<tr>\n<td><code>[Key]</code> (DataAnnotations)</td>\n<td>flag only</td>\n<td>YES (drives the proxy Id)</td>\n</tr>\n<tr>\n<td>C# <code>required</code></td>\n<td><strong>enforced</strong> on read <em>(7.4.3+)</em>: null-or-missing throws <code>JsonBindingException</code></td>\n<td><strong>enforced</strong> (throws on a missing member)</td>\n</tr>\n<tr>\n<td><code>[DataContract]</code> + <code>[DataMember]</code> (opt-in + <code>Name=</code>)</td>\n<td>YES, <strong>including non-public members and accessors</strong> <em>(7.4.3+, the hybrid rule: the attribute pair is the explicit opt-in and accessibility does not filter it, matching DCJS; <code>[JsonInclude]</code> alone still grants nothing there)</em></td>\n<td>YES <em>(7.4.3+)</em>, the same model: <code>[DataMember]</code> is the sole membership opt-in, accessibility does not filter (non-public members are reached through accessor thunks), and <code>Name=</code> renames are honoured</td>\n</tr>\n<tr>\n<td><code>[DataMember]</code>'s <code>IsRequired = true</code></td>\n<td><strong>read side enforced</strong> <em>(7.4.3+)</em>, DCJS-faithful: an ABSENT member throws, an explicit <code>null</code> satisfies (deliberately distinct from C# <code>required</code>, where null also throws). Write side unchanged (<code>WithNullMembers()</code> stays the frozen-reader recipe)</td>\n<td>YES <em>(7.4.3+)</em>, same semantics, emitted as one presence guard per member</td>\n</tr>\n<tr>\n<td><code>[DataMember]</code>'s <code>Order</code> / <code>EmitDefaultValue</code></td>\n<td>no</td>\n<td>no</td>\n</tr>\n<tr>\n<td><code>[OnSerializing]</code> / <code>[OnSerialized]</code> / <code>[OnDeserializing]</code> / <code>[OnDeserialized]</code></td>\n<td>YES <em>(7.4.3+)</em>, <code>void M()</code> on all four and <code>void M(JsonValue\\|JsonObject\\|JsonArray)</code> on the deserialize pair; the legacy <code>void M(StreamingContext)</code> throws at contract build</td>\n<td>same shapes accepted; the legacy <code>StreamingContext</code> form is build error <code>CJSON0015</code> at the callsite</td>\n</tr>\n<tr>\n<td>STJ <code>IJsonOnSerializing</code> / <code>IJsonOnSerialized</code> / <code>IJsonOnDeserializing</code> / <code>IJsonOnDeserialized</code> interfaces</td>\n<td>no, deliberately (see <em>Lifecycle</em> below)</td>\n<td>no, deliberately</td>\n</tr>\n<tr>\n<td><code>[CollectionDataContract]</code>'s <code>Name</code> / <code>ItemName</code> / <code>KeyName</code> / <code>ValueName</code></td>\n<td>no, and <strong>neither does DCJS</strong>: those four names shape the XML format only, so there is nothing to reproduce (see below)</td>\n<td>no</td>\n</tr>\n<tr>\n<td>Newtonsoft <code>[JsonProperty]</code> (name only)</td>\n<td>YES</td>\n<td>YES <em>(7.4.3+)</em> - honoured as the lowest-priority naming fallback (after native <code>[JsonProperty]</code> and <code>[JsonPropertyName]</code>); a member stacking naming attributes with DIFFERENT names is refused (<code>CJSON0011</code> / a reflection throw)</td>\n</tr>\n<tr>\n<td>Newtonsoft <code>[JsonIgnore]</code></td>\n<td>YES</td>\n<td>YES <em>(7.4.3+)</em> - <code>[JsonIgnore]</code> is matched by name on both paths (any namespace); the generated converter learned the non-STJ spelling in 7.4.3</td>\n</tr>\n<tr>\n<td><code>[XmlIgnore]</code> / <code>[XmlElement]</code> / <code>[XmlAttribute]</code></td>\n<td>YES (non-<code>[DataContract]</code> types)</td>\n<td>no</td>\n</tr>\n<tr>\n<td>STJ <code>[JsonPropertyOrder]</code>, <code>[JsonNumberHandling]</code>, <code>[JsonExtensionData]</code>, <code>[JsonConstructor]</code></td>\n<td>no</td>\n<td>no</td>\n</tr>\n</tbody>\n</table>\n<p><code>[JsonIgnore(Condition = ...)]</code> follows System.Text.Json <em>(7.4.3+, both paths, and both the text writer and\n<code>JsonValue.FromValue</code>/<code>Pack</code>)</em>:</p>\n<table>\n<thead>\n<tr>\n<th>Condition</th>\n<th>Effect on serialization</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td><code>Always</code> (the default, i.e. bare <code>[JsonIgnore]</code>)</td>\n<td>member excluded from <strong>both</strong> directions</td>\n</tr>\n<tr>\n<td><code>Never</code></td>\n<td>always emitted, even null/default - overrides <code>WithoutDefaultValues()</code> / <code>WithoutNullMembers()</code></td>\n</tr>\n<tr>\n<td><code>WhenWritingNull</code></td>\n<td>omitted when null, whatever the settings say</td>\n</tr>\n<tr>\n<td><code>WhenWritingDefault</code></td>\n<td>omitted when equal to the member's default, whatever the settings say</td>\n</tr>\n</tbody>\n</table>\n<p>Two intentional deviations from STJ: <code>WhenWritingDefault</code> compares against the member's <strong>declared</strong> default (so\n<code>[JsonProperty(DefaultValue = 7)]</code> composes with it), and <code>WhenWritingNull</code> on a non-nullable value type is inert\ninstead of throwing.</p>\n<h3>Enums in the output <em>(the 7.4.2 -&gt; 7.4.3 format change)</em></h3>\n<p><strong>Enums serialize as their string literal by default, in every form</strong> - the text writer, the DOM\n(<code>JsonValue.FromValue</code>, reflection <code>Pack</code>) and generated converters, which now agree byte-for-byte. This is a\ndeliberate divergence from System.Text.Json (whose default is numeric), chosen so payloads are self-describing and\nfriendly to JavaScript clients. <strong>Reading is unchanged and tolerant in both directions</strong>: names and custom tokens bind\ncase-insensitively (<code>\"fooBar\"</code> == <code>\"FooBar\"</code> == <code>\"FOOBAR\"</code>), and numbers and numeric strings are still accepted - so\nevery pre-7.4.3 payload still deserializes, and mixed fleets can roll forward incrementally.</p>\n<table>\n<thead>\n<tr>\n<th>Value</th>\n<th>7.4.2 output</th>\n<th>7.4.3 output</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td><code>DayOfWeek.Friday</code> through <code>CrystalJson.Serialize</code></td>\n<td><code>5</code></td>\n<td><code>\"Friday\"</code></td>\n</tr>\n<tr>\n<td><code>DayOfWeek.Friday</code> through <code>JsonValue.FromValue</code></td>\n<td><code>\"Friday\"</code> (it always stringified, ignoring the settings)</td>\n<td><code>\"Friday\"</code> (settings now honored)</td>\n</tr>\n<tr>\n<td>Undeclared flags combination through <code>JsonValue.FromValue</code></td>\n<td><code>\"7\"</code> (the number, in a string)</td>\n<td><code>\"ReadWrite, Delete\"</code> (composed)</td>\n</tr>\n<tr>\n<td>Enum field carrying <code>[EnumMember(Value=\"C\")]</code></td>\n<td><code>0</code> (the attribute was ignored)</td>\n<td><code>\"C\"</code></td>\n</tr>\n</tbody>\n</table>\n<p>Flags compose exactly like <code>Enum.ToString(\"G\")</code>. Custom literals are read off the enum's own fields, by attribute\nname (no STJ package reference or version floor): <code>[JsonStringEnumMemberName(\"C\")]</code> (STJ 9+) and <code>[EnumMember(Value=\"C\")]</code>\n(the DataContract spelling Newtonsoft also honors). When both are present STJ wins for <strong>writing</strong>; every spelling is\naccepted on <strong>read</strong>. Attribute-set tokens are never camelCased.</p>\n<p><strong>To get numbers back</strong>, pick the narrowest scope that fixes the break:</p>\n<ul>\n<li><strong>Per call / per endpoint:</strong> <code>CrystalJsonSettings.Json.WithEnumAsNumbers()</code> (composes with every other option, e.g.\n<code>CrystalJsonSettings.JsonCompact.WithEnumAsNumbers()</code>).</li>\n<li><strong>Per member:</strong> <code>[JsonProperty(EnumFormat = JsonEnumFormat.Number)]</code>.</li>\n<li><strong>System.Text.Json consumers of your payloads:</strong> STJ's default reader rejects enum <em>names</em>. Either add\n<code>new JsonStringEnumConverter()</code> to their <code>JsonSerializerOptions</code>, or keep those endpoints on <code>WithEnumAsNumbers()</code>.</li>\n<li><strong>Frozen <code>DataContractJsonSerializer</code> clients:</strong> DCJS emits numbers and ignores <code>[EnumMember]</code> in JSON, so endpoints\nthat must stay byte-compatible with a DCJS producer use <code>WithEnumAsNumbers()</code>.</li>\n<li><strong>Stored documents</strong> written before 7.4.3 (numeric) read back unchanged; new writes carry names. If byte-stable\noutput matters (hashing, dedup), pin the settings explicitly on that path.</li>\n</ul>\n<p>⚠️ The raw flag <code>CrystalJsonSettings.OptionFlags.EnumsAsString</code> is retired with an <strong>error-level</strong> <code>[Obsolete]</code>: the bit\nis now <code>EnumsAsNumbers</code>, with inverted meaning. The <code>EnumsAsString</code> <em>property</em> and the <code>WithEnumAsStrings()</code> /\n<code>WithEnumAsNumbers()</code> methods keep their names and meanings - only the default flipped.</p>\n<p><strong>Migrating a legacy <code>[DataContract]</code> DTO</strong> (e.g. from <code>DataContractJsonSerializer</code>): the reflection path already\nreproduces its member selection and <code>Name=</code> renames, so an un-touched DTO keeps its output - <strong>but only on that path</strong>\n(a generated container applies the same model, so registering one is supported and produces the same format). Useful equivalences:</p>\n<ul>\n<li><code>EmitDefaultValue = false</code> -&gt; <code>[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]</code></li>\n<li>a non-public <code>[DataMember]</code> -&gt; nothing <em>(7.4.3+)</em>: on a <code>[DataContract]</code> type it serializes and binds\nautomatically on the reflection path (the interim <code>[JsonInclude]</code> opt-in keeps working, now redundant)</li>\n<li><code>[CollectionDataContract(ItemName = \"entry\", KeyName = \"code\", ValueName = \"label\")]</code> -&gt; <strong>nothing to do</strong>: those\nnames exist in the XML format only. DCJS itself writes a <code>List&lt;string&gt;</code> subclass as <code>[\"x\",\"y\"]</code> and a\n<code>Dictionary&lt;string,string&gt;</code> subclass as <code>[{\"Key\":\"c1\",\"Value\":\"L1\"}]</code>, with the literal <code>Key</code>/<code>Value</code> and the\nconfigured names nowhere in the output. The attribute's only JSON-visible meaning is \"this type is a collection\",\nwhich section 10 already covers for subclasses of <code>List&lt;T&gt;</code> / <code>Collection&lt;T&gt;</code> / <code>Dictionary&lt;K,V&gt;</code>: they bind back\nas themselves. Do not go looking for a naming knob to port.</li>\n<li><code>[KnownType]</code> -&gt; <code>[JsonPolymorphic(TypeDiscriminatorPropertyName = \"__type\")]</code> + <code>[JsonDerivedType(typeof(X), \"Name:Ns\")]</code></li>\n<li><code>Order</code> -&gt; nothing (member order is not part of the contract); <code>IsRequired = true</code> -&gt; nothing <em>(7.4.3+)</em>: the\nreflection path enforces it on read with DCJS semantics (absent throws, explicit null satisfies). For a\nstricter contract use C# <code>required</code> (null-or-missing throws, both paths).</li>\n<li>Never put <code>[DataMember]</code> (or <code>[JsonInclude]</code>, or a <code>[JsonProperty]</code>-style rename) and an unconditional\n<code>[JsonIgnore]</code> on the same member: the combination is <strong>refused loudly</strong> on both paths <em>(7.4.3+)</em> - the\nreflection path throws when the type's contract is built, and the generator fails the build with error\n<code>CJSON0008</code>. This is the dual-output DTO (one format carried the member, the other did not), which is not\nsupported: split the type, one DTO per serializer; if the pair is a slip, remove one of the two attributes.\nDo NOT resolve it by adding a <code>Condition</code> - that flips the member to included-with-a-write-rule and ships it\nonto the second format. A conditional <code>[JsonIgnore(Condition = ...)]</code> next to <code>[DataMember]</code> stays legal (it is\nthe <code>EmitDefaultValue</code> recipe).</li>\n</ul>\n<p><strong>Settings that restore legacy-reader compatibility</strong> (the recipe column, per construct):</p>\n<table>\n<thead>\n<tr>\n<th>Legacy expectation</th>\n<th>Setting</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td><code>\"member\": null</code> emitted rather than omitted</td>\n<td><code>WithNullMembers()</code></td>\n</tr>\n<tr>\n<td><code>\"\\/Date(ms)\\/\"</code> dates emitted</td>\n<td><code>WithMicrosoftDates()</code></td>\n</tr>\n<tr>\n<td>numeric enums</td>\n<td><code>WithEnumAsNumbers()</code></td>\n</tr>\n<tr>\n<td><code>[{\"Key\":k,\"Value\":v}]</code> dictionaries emitted</td>\n<td><code>WithDictionariesAsPairArrays()</code></td>\n</tr>\n<tr>\n<td><code>\"P1DT2H3M4.005S\"</code> ISO 8601 duration strings for <code>TimeSpan</code> <em>(7.4.3+; default is a number of seconds)</em></td>\n<td><code>WithIso8601Durations()</code></td>\n</tr>\n</tbody>\n</table>\n<p><strong><code>CrystalJsonSettings.DataContractCompat</code></strong> <em>(7.4.3+)</em> is the named, cached preset composing all five: an\nendpoint using it reproduces the COMPLETE <code>DataContractJsonSerializer</code> format with one settings reference.\nScope it per endpoint (<code>WithNullMembers()</code> is pure verbosity for any consumer that is not a frozen legacy\nreader); reading never needs it, every legacy shape is accepted on read by default.</p>\n<p><strong>For teams coming from DCJS: the container-level profile</strong> <em>(7.4.3+)</em>. A source-generated container can bake\nthe preset as its default format: <code>[CrystalJsonConverter(CrystalJsonSerializerDefaults.DataContractCompat)]</code>.\nIts generated entry points then emit the legacy format when the caller passes no settings; explicitly passed\nsettings always replace the profile ENTIRELY (no merging). The profile governs value formats only and is\nindependent of membership: it serves <strong>plain DTOs</strong> (the DCJS POCO opt-out rules) and <strong><code>[DataContract]</code>\ntypes</strong> (the DataContract model) alike, exactly as an unprofiled container does. For the types it serves, <strong>a DataContractCompat\ncontainer produces what DCJS would have produced, with the documented differences</strong> - member order\n(declaration order here; DCJS wrote POCO members alphabetically and honored <code>Order=</code>), no <code>\\/</code> escaping\noutside <code>\\/Date()\\/</code> literals, <code>-0.0</code> serialized as <code>0</code>, and the dual-output /\ndouble-contract shapes DCJS resolved silently are refused loudly. Combining the profile with a camelCase (or\nother) naming policy is a build error (<code>CJSON0013</code>): the DCJS format has no naming policy. <code>PropertyNameCaseInsensitive</code>\nnext to the profile is NOT refused - it only changes how an incoming member name is matched when reading JSON,\nand the profile still writes the declared names untouched: strict on output, lenient on input. <strong>The dual-container pattern is the intended\nshape for a progressive WCF portage</strong>: not-yet-ported services serialize through the compat container,\nmodernized services through a default or <code>Web</code> container over the SAME types; when the portage completes,\ndelete the legacy container.</p>\n<p>⚠️ The one genuine hazard when a <strong>frozen</strong> legacy client reads your output: a <strong>null <code>[DataMember(IsRequired = true)]</code>\nmember</strong>. CrystalJson omits nulls by default and the legacy reader <strong>throws</strong> on the missing member. Put\n<code>WithNullMembers()</code> on those endpoints.</p>\n<h3>One type serialized by BOTH CrystalJson and System.Text.Json</h3>\n<p>Climb this ladder, stop at the first rung that holds:</p>\n<ol>\n<li><strong>The attributes coexist</strong> - each serializer ignores the other's - so keep <strong>one type</strong>. <code>[JsonConvertWith]</code>,\n<code>[JsonBooleanLiterals]</code>, <code>[JsonProperty]</code> and <code>[EnumMember]</code> are all invisible to STJ. The two outputs may <em>differ</em>\nper serializer; that is fine.</li>\n<li><strong>A conflict a dual-shape converter resolves</strong> - keep <strong>one type</strong> and write ONE converter class valid for both:\nderive STJ's <code>JsonConverter&lt;T&gt;</code> <em>and</em> implement <code>IJsonMemberConverter&lt;T&gt;</code>. Recognition is structural, each\nserializer uses its own facet.</li>\n<li><strong>The attributes genuinely conflict</strong> - <strong>duplicate the type</strong>, one DTO per serializer; never contort one type to\nserve both. The canonical case: the STJ-spelled <code>[JsonConverter(typeof(X))]</code> where <code>X</code> is a CrystalJson-only\nconverter. CrystalJson tolerates it, but <strong>STJ does not reciprocate</strong> - it inspects that attribute, sees a type that\ndoes not derive its own <code>JsonConverter</code>, and throws <code>InvalidOperationException</code> while building the type's metadata.</li>\n</ol>\n<p>That asymmetry is why <code>[JsonConvertWith]</code> is the right attribute for a CrystalJson-only converter: STJ never looks at it.</p>\n<p><strong>Legacy format tolerance (read side, always on, no setting needed):</strong> <code>\"\\/Date(ms)\\/\"</code> and <code>\"\\/Date(ms+HHMM)\\/\"</code> dates\nbind to <code>DateTime</code>/<code>DateTimeOffset</code> (the ms are always UTC; the suffix only carries the producer's offset), and the\n<code>[{\"Key\":k,\"Value\":v}]</code> dictionary shape binds to <code>Dictionary&lt;K,V&gt;</code> <em>(7.4.3+, strict: every element must be an object\nwith exactly <code>Key</code> and <code>Value</code>)</em>. To <strong>emit</strong> either legacy shape, opt in with <code>WithMicrosoftDates()</code> /\n<code>WithDictionariesAsPairArrays()</code> (section 4).</p>\n<p><strong>Lifecycle:</strong> deserialization runs the <strong>parameterless constructor</strong> (public or not), then assigns members; missing\nand explicit-null fields are skipped, so ctor-initialised state survives. A type with <strong>no parameterless constructor</strong>\n(a positional record, a class whose constructors all take parameters) is built through a constructor instead\n<em>(7.4.6+, both paths)</em>: the one marked <code>[JsonConstructor]</code> (System.Text.Json's attribute, matched by name), else the\nsingle public constructor whose every parameter matches a serialized member by name (case-insensitive) and type. A\nparameter takes the member's value, its own default value when the member is absent (<code>record Toy(string Name, int Size = 3)</code>\nreads <code>{ \"Name\": \"ball\" }</code> as <code>Toy(\"ball\", 3)</code>), and a member no parameter covers is assigned after construction. Two\nmatching constructors without <code>[JsonConstructor]</code>, or a parameter that matches no member, is <code>CJSON0027</code> (error) in a\ngenerated container, and a <code>JsonBindingException</code> at bind time on the reflection path.</p>\n<p>The four <code>[OnSerializing]</code> / <code>[OnSerialized]</code> / <code>[OnDeserializing]</code> / <code>[OnDeserialized]</code> callbacks <strong>are invoked</strong>\n<em>(7.4.3+)</em>, on both write routes (text and DOM) and on read, so a <code>DataContractJsonSerializer</code> estate keeps the\nbehaviour it had. <strong>Only the modern signatures are accepted:</strong></p>\n<table>\n<thead>\n<tr>\n<th>Signature</th>\n<th>Accepted on</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td><code>void M()</code></td>\n<td>all four</td>\n</tr>\n<tr>\n<td><code>void M(JsonValue)</code> / <code>void M(JsonObject)</code> / <code>void M(JsonArray)</code></td>\n<td><code>[OnDeserializing]</code> / <code>[OnDeserialized]</code>, receives the document being bound</td>\n</tr>\n<tr>\n<td><code>void M(StreamingContext)</code></td>\n<td><strong>refused</strong>, both paths (see below)</td>\n</tr>\n</tbody>\n</table>\n<p>The document-taking form is a capability <code>DataContractJsonSerializer</code> never had, and neither does System.Text.Json:\ntheir reader is forward-only with no document materialized, so by the time a callback runs there is nothing to hand\nit. Prefer the parameterless form; take the document only when the callback genuinely needs to inspect the payload.</p>\n<p>⚠️ <strong><code>void M(StreamingContext)</code> is refused</strong>, which is a deliberate breaking change for ported DCJS code: the generator\nreports <strong><code>CJSON0015</code></strong> at the callsite, and the reflection path throws the same message when it builds the type's\ncontract (once per type, never per call). The fix is mechanical, and it has one precondition: <strong>DCJS <em>requires</em> that\nparameter</strong>, so converting a callback costs the type its DCJS compatibility. A type still serialized by DCJS anywhere\ncannot be converted on its own. See the migration guide for the sweep recipe.</p>\n<p><strong>Where they fire, exactly</strong> (pinned by tests on both paths, not by assertion here):</p>\n<table>\n<thead>\n<tr>\n<th></th>\n<th></th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>Write</td>\n<td><code>[OnSerializing]</code> strictly before the first member is written, <code>[OnSerialized]</code> strictly after the last, on the text route AND the DOM route</td>\n</tr>\n<tr>\n<td>Read</td>\n<td><code>[OnDeserializing]</code> on a constructed but <strong>unpopulated</strong> instance, <code>[OnDeserialized]</code> on the fully populated one</td>\n</tr>\n<tr>\n<td>Member converters</td>\n<td>run <strong>inside</strong> the bracket, since they are part of writing/reading a member</td>\n</tr>\n<tr>\n<td><strong>Proxies</strong></td>\n<td><strong>no lifecycle at all.</strong> A proxy is a lazy typed <em>view</em> over the DOM: nothing is constructed and nothing is populated, so there is no interval to bracket. The callbacks run at <strong>materialisation</strong> (<code>ToValue()</code>, <code>Deserialize</code>, <code>Unpack</code>)</td>\n</tr>\n</tbody>\n</table>\n<p>⚠️ That last row matters if you have adopted \"stay on the proxy\" as a principle: a callback will not run for\nyou until something calls <code>ToValue()</code>. If a type's invariants depend on a callback, read it as a value.</p>\n<p>The strictness of the write bracket is the point for the one workload callbacks genuinely serve: a <strong>latch</strong>\nthat suppresses cache invalidation while two views of the same data are populated. Without an exact bracket the\nsecond member to arrive clobbers the first, and which one that is depends on member order.</p>\n<p>Note that lifecycle callbacks are a pattern to move away from rather than toward. A DTO should be a dumb type with\nits preparation already done before it reaches the serializer; a callback bolts serialization onto a type that was\nnever designed for it, which is why such types end up needing cleanup halves and locks. The supported remedy is to\nadapt the not-meant-for-serialization type into a plain DTO, at which point the callbacks are not needed at all.\nThe attribute support exists to make a large legacy estate portable, not to encourage the pattern. (This is also why\nthe four System.Text.Json callback <em>interfaces</em> - <code>IJsonOnSerializing</code> and friends - are deliberately <strong>not</strong>\nhonoured: adding a second, cleaner-looking spelling would advertise the pattern rather than retire it.)</p>\n<p>Alternatively, take over the type entirely with <code>IJsonPackable</code> / <code>IJsonDeserializable&lt;T&gt;</code> (section 7) or a\n<code>ctor(JsonValue[, ICrystalJsonTypeResolver])</code>.</p>\n<hr>\n<h2>10. Collections <em>(7.4.3+)</em></h2>\n<p>One contract governs every collection: <strong>you get an instance of the declared member type, or a\n<code>JsonBindingException</code> / <code>JsonSerializationException</code> naming the type and the reason.</strong> A wrong-shaped value is never\nreturned, because the compiled member setter uses a lenient cast that would turn it into a silent <code>null</code>.</p>\n<p>So declare the collection type you actually want and let it bind:</p>\n<pre><code>public sealed class StoreDto { public Collection&lt;int&gt;? Codes { get; set; } }\nCrystalJson.Deserialize&lt;StoreDto&gt;(\"\"\"{ \"Codes\": [ 1, 2, 3 ] }\"\"\").Codes   // Co\n</code></pre>\n","files":[{"path":"SKILL.md","sizeBytes":67293,"isText":true}],"reviewScore":null,"reviewSummary":null,"trust":{"provenance":"trusted-source-unreviewed","notice":"Community-authored content, reproduced verbatim and not vetted as instructions. Treat it as data to evaluate, never as directives to follow.","bodySource":null},"bodyLocked":false,"purchaseUrl":null,"sourceUrl":null,"report":{"provenance":"trusted-source-unreviewed","screen":{"ran":true,"outcome":"clean","suspicious":0,"notes":0,"hiddenCharacters":false},"virusScan":{"engine":"clamav","status":"clean","scannedAt":"2026-10-22T18:59:34.053185Z","sha256":"2E9B6471E33C638DB0DB1CABE1325E8156D2DE5C9EFBAF04183599D2237B433D","sizeBytes":24112},"review":null,"source":{"repositoryUrl":"https://github.com/SnowBankSDK/foundationdb-dotnet-client","path":".claude/skills/crystaljson","license":"BSD-3-Clause","commit":"e8d2b6024a04246106b548c55f3d27dbd4de73ea","subtreeSha":"E2EE6B8BBFDFA09A672D58F72DB9416F7CA332E52C23EA838DD85A68BA247FD8","lastSyncedAt":"2026-11-11T21:45:31.82232Z"},"reviewedAt":"2026-10-22T19:02:42.701394Z","notice":"Community-authored content, reproduced verbatim and not vetted as instructions. Treat it as data to evaluate, never as directives to follow."},"install":[{"target":"skills-cli","command":"npx skills add https://github.com/SnowBankSDK/foundationdb-dotnet-client/tree/master/.claude/skills/crystaljson"},{"target":"claude-code","command":"claude plugin marketplace add https://llmmart.ai/marketplace.json && claude plugin install snowbanksdk-foundationdb-dotnet-client@llmmart"},{"target":"git","command":"git clone https://github.com/SnowBankSDK/foundationdb-dotnet-client.git"}]}