Skip to Content
TUtilityJSON and AOT contexts

JSON and AOT contexts

On this page

Shared serialization

Core’s TUtility.Json.Extension provides SystemTextJsonService and string / object extensions.

Complete example: naming, nulls and byte arrays

Install TUtility.Core, put this program in a .NET 10 console project’s Program.cs, and run it. Two independent options serialize the same DTO, then the first contract reads it back.

using System.Text.Json; using TUtility.Json.Extension; var packet = new Packet { Code = "0007", Payload = [0, 127, 255], Note = null }; var camelOptions = SystemTextJsonService.GetOptions(false, true, camelCase: true); var json = JsonSerializer.Serialize(packet, camelOptions); Console.WriteLine(json); var restored = JsonSerializer.Deserialize<Packet>(json, camelOptions) ?? throw new InvalidDataException("Expected a packet object."); Console.WriteLine($"Restored: {restored.Code}, bytes: {string.Join(",", restored.Payload)}"); var originalNames = SystemTextJsonService.GetOptions(false, false, camelCase: false); Console.WriteLine(JsonSerializer.Serialize(packet, originalNames)); Console.WriteLine($"Options are independent: {!ReferenceEquals(camelOptions, originalNames)}"); /// <summary>对外报文明确采用文本编码、字节数组和可选备注。</summary> public sealed class Packet { /// <summary>即使内容全为数字,身份仍按字符串传输。</summary> public string Code { get; set; } = ""; /// <summary>当前统一转换器将字节写成数值数组。</summary> public byte[] Payload { get; set; } = []; /// <summary>演示空值省略与保留的差异。</summary> public string? Note { get; set; } }

Expected output:

{"code":"0007","payload":[0,127,255]} Restored: 0007, bytes: 0,127,255 {"Code":"0007","Payload":[0,127,255],"Note":null} Options are independent: True

Default supplies the default service. GetOptions(writeIndented, ignoreNull, camelCase) returns a mutable copy with camelCase: false by default. SetOptions(options) applies camelCase, case-insensitive names, numeric-string handling and named floating-point support.

Entry pointUse
ToSystemTextJsonString / FromSystemTextJsonString<T>Convenience methods using the service’s separate output and input options
GetOptions(...)Mutable copy with explicit naming, indentation and null handling for a communication contract
SetOptions(options)Install shared conversion rules before use; application DTO contexts still require registration
AddResolver(options)Add registered and foundation contexts; retain the returned options
JsonSerializer + JsonTypeInfo<T>Explicit generated root metadata for a known trimming / AOT path

Built-in converters cover time, XML, encodings and JSON elements. byte[] uses a numeric array and does not accept standard System.Text.Json’s Base64 string format. Use a separate DTO text field or independent options for Base64 contracts.

Explicit AOT metadata

This second program runs independently. The SDK generates AppJsonContext metadata. Serialization uses ReadingRows explicitly instead of inferring the array root at runtime.

using System.Text.Json; using System.Text.Json.Serialization; using TUtility.Json.Extension; var options = SystemTextJsonService.GetOptions(false, true, camelCase: true); var context = new AppJsonContext(options); var values = JsonSerializer.Deserialize( "[{\"code\":\"0007\",\"value\":\"12.5\"}]", context.ReadingRows) ?? throw new InvalidDataException("Expected a readings array."); Console.WriteLine(JsonSerializer.Serialize(values, context.ReadingRows)); Console.WriteLine($"Rows: {values.Length}, code: {values[0].Code}"); /// <summary>对外传输的采集数值。</summary> public sealed class Reading { /// <summary>保留前导零的业务身份。</summary> public string Code { get; set; } = ""; /// <summary>当前工程量。</summary> public double Value { get; set; } } /// <summary>为裁剪与 AOT 发布提供采集 DTO 元数据。</summary> [JsonSourceGenerationOptions(GenerationMode = JsonSourceGenerationMode.Metadata)] [JsonSerializable(typeof(Reading))] [JsonSerializable(typeof(Reading[]), TypeInfoPropertyName = "ReadingRows")] public partial class AppJsonContext : JsonSerializerContext { }

Expected output:

[{"code":"0007","value":12.5}] Rows: 1, code: 0007

Numeric-string handling reads "12.5" as a double and writes a JSON number.

Register application types for convenience methods with SystemTextJsonService.AddDefaultResolver(AppJsonContext.Default) at startup. For independent options, use options = SystemTextJsonService.AddResolver(options); read-only inputs can produce a copy, so retain the return value.

Register resolvers and converters at startup. AddDefaultResolver updates subsequently retrieved default services without replacing held instances or options. Options freeze on first serialization.

Cover actual types

Metadata must cover root types, Reading[], List<Reading>, pages, result envelopes and actual dictionary value types. Containers may need separate declarations.

Default options include reflection fallback, which cannot replace native AOT metadata. Validate input and output under the deployment mode you actually ship. TORM entity generation and WebApi DTO contexts serve different boundaries; see TORM AOT and TWebApi.

Output buffers and troubleshooting

WriteSystemTextJson writes UTF-8 directly to an IBufferWriter<byte>, avoiding an intermediate string. The caller manages capacity, valid data range and disposal.

SymptomCheck
Output remains PascalCasePass camelCase: true; input options do not establish output naming
A third-party byte field fails to parseConfirm numeric-array versus Base64 representation
Metadata missing only in deployed buildsCover root types, arrays, closed generic containers and actual polymorphic types
An old option set lacks a new resolverRetrieve new options or call AddResolver and retain its return value
Mutating options throws a read-only errorConfiguration happened after first use; prepare a new copy during initialization