Csharpessentials json

From senrecep/CSharpEssentials · View interactive version

Csharpessentials json is an AI agent skill from the GitHub repository senrecep/CSharpEssentials. Use when configuring System.Text.Json. Covers EnhancedJsonSerializerOptions presets (DefaultOptions, StrictOptions, ApplyTo), ConvertToJson/ConvertFromJson helpers, AddEnumConventions for [StringEnum] enums (obsolete ConditionalStringEnumConverter and StringEnumNaming), polymorphism with [JsonTypeDi

How to use this skill

Skill file

CSharpEssentials.Json

Pre-configured System.Text.Json options, converters and serialization helpers. Targets net11.0, net10.0, net9.0 and netstandard2.1; depends on CSharpEssentials.Enums.

Installation

dotnet add package CSharpEssentials.Json

Namespace

using System.Text.Json;
using CSharpEssentials.Json;

EnhancedJsonSerializerOptions

| Member | Contents |

|---|---|

| DefaultOptionsWithoutConverters | Web defaults, camelCase, case-insensitive reads, nulls ignored on write, ReferenceHandler.IgnoreCycles, relaxed escaping |

| DefaultOptions | The above plus enum conventions (AddEnumConventions(EnumConventions.Default), Data mode), MultiFormatDateTimeConverterFactory, PolymorphicJsonConverterFactory and AddPolymorphismWithReflection() |

| DefaultOptionsWithDateTimeConverter | DefaultOptionsWithoutConverters plus MultiFormatDateTimeConverterFactory |

| StrictOptions | Case-sensitive; rejects trailing commas, comments and unmapped members; AddPolymorphismWithReflection() |

| CreateOptionsWithConverters(params JsonConverter[]) | DefaultOptionsWithoutConverters plus the given converters |

| options.Create(configure) | Copies the options and applies configure to the copy |

| source.ApplyTo(target) / target.ApplyFrom(source) | Copies settings and converters onto another instance. The target keeps its own TypeInfoResolver when it has one, and gets the source's polymorphism added to it |

The preset instances become read-only after first use; call Create for a modifiable copy. The class is [RequiresUnreferencedCode] / [RequiresDynamicCode] because its presets find polymorphic derived types with reflection.

// ASP.NET Core Minimal APIs
builder.Services.ConfigureHttpJsonOptions(o =>
    EnhancedJsonSerializerOptions.DefaultOptions.ApplyTo(o.SerializerOptions));

string json = JsonSerializer.Serialize(order, EnhancedJsonSerializerOptions.DefaultOptions);

Serialization helpers

All helpers except string.ConvertToJsonDocument() use DefaultOptions when no options are passed. They use reflection-based serialization; in trimmed or AOT apps call JsonSerializer with a JsonSerializerContext.

string json = order.ConvertToJson();
Order? back = json.ConvertFromJson<Order>();
object? untyped = json.ConvertFromJson(typeof(Order));
using JsonDocument document = order.ConvertToJsonDocument();

// JsonElement to plain CLR values (Dictionary<string, object?>, List<object?>, int/long/decimal/double, string, bool, null)
object? clr = document.RootElement.ToClrObject();

Enum conventions

AddEnumConventions adds the enum converter for enums with generated metadata ([StringEnum] from CSharpEssentials.Enums). Other enums keep the converters already on the options, so a plain enum stays a number unless you add JsonStringEnumConverter. DefaultOptions already applies it in Data mode.

using CSharpEssentials.Enums;

JsonSerializerOptions data = new JsonSerializerOptions(JsonSerializerDefaults.Web)
    .AddEnumConventions(EnumConventions.Default);                       // Data: tolerant, [EnumFallback] member for unknown values

JsonSerializerOptions input = new JsonSerializerOptions(JsonSerializerDefaults.Web)
    .AddEnumConventions(EnumConventions.Default, EnumReadMode.Input);   // Input: strict, throws EnumValueJsonException

// [StringEnum] OrderStatus.Shipped -> "shipped"
// Plain enum value                 -> 2

Polymorphism

The base type picks the path:

[JsonPolymorphic(TypeDiscriminatorPropertyName = "$event")]
public interface IEvent;

[JsonTypeDiscriminator("order.placed.v1")]
public sealed record OrderPlaced(Guid Id, decimal Total) : IEvent;

var options = new JsonSerializerOptions(JsonSerializerDefaults.Web) { TypeInfoResolver = new DefaultJsonTypeInfoResolver() }
    .AddPolymorphism();
// {"$event":"order.placed.v1","id":"...","total":10}

// Source-generated context: copy its options, list every derived type with [JsonSerializable], call AddPolymorphism last
var aot = new JsonSerializerOptions(AppJsonContext.Default.Options).AddPolymorphism();

MultiFormatDateTimeConverterFactory

Reads DateTime and DateTime? from a fixed list of 35 formats (ISO 8601, dd.MM.yyyy, MM/dd/yyyy, March 14, 2024, RFC 1123 and more) and from numeric Unix-seconds strings. Constructor arguments add formats. Every value is returned as UTC (Kind = Utc); input without an offset is read as UTC. Slash dates try dd/MM/yyyy before MM/dd/yyyy. Writes use yyyy-MM-ddTHH:mm:ss.ffffffzzz, and an Unspecified value is written as UTC. ISO text with 1 to 7 fraction digits is read, including the O round-trip form System.Text.Json writes.

var options = new JsonSerializerOptions();
options.Converters.Add(new MultiFormatDateTimeConverterFactory("dd.MM.yyyy HH-mm"));

Best practices

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.