Skip to main content

JsonWebKeyConverter Class

Abblix.Jwt

Abblix.Jwt

JsonWebKeyConverter Class

Custom JSON converter for JsonWebKey that handles polymorphic serialization/deserialization based on the "kty" (key type) discriminator while ensuring the KeyType property is serialized in both polymorphic and direct serialization scenarios.

public class JsonWebKeyConverter : System.Text.Json.Serialization.JsonConverter<Abblix.Jwt.JsonWebKey>

Inheritance System.ObjectSystem.Text.Json.Serialization.JsonConverterSystem.Text.Json.Serialization.JsonConverter<JsonWebKey> → JsonWebKeyConverter

Remarks

Looks superficially replaceable by [JsonPolymorphic(TypeDiscriminatorPropertyName = "kty")]

  • [JsonDerivedType]. It is not, because of how this hierarchy emits "kty" today: each concrete subtype overrides KeyType with [JsonPropertyName("kty")] and [JsonInclude], which guarantees "kty" appears both in polymorphic writes (JsonSerializer.Serialize<JsonWebKey>(rsaKey)) and in direct concrete-type writes (JsonSerializer.Serialize(rsaKey) where the compile-time type is RsaJsonWebKey).

Switching to [JsonPolymorphic] alone breaks one of those two scenarios:

  • Keep the derived [JsonInclude] override AND add [JsonPolymorphic] → "kty" gets written twice in polymorphic context (once by STJ as the discriminator, once by the derived property), producing invalid JSON.
  • Drop the derived [JsonInclude] override → "kty" disappears whenever a concrete subtype is serialized directly, because [JsonPolymorphic] only writes the discriminator when STJ sees the abstract base type.

This converter bridges both write modes by always serializing through the concrete subtype's own attribute set, so "kty" lands once regardless of the call site. A future replacement is possible but must also touch every KeyType override and ship with a round-trip regression test that covers polymorphic AND direct serialization paths.

Methods

JsonWebKeyConverter.Read(Utf8JsonReader, Type, JsonSerializerOptions) Method

Reads a JsonWebKey from the JSON payload, dispatching to the matching concrete subtype (RsaJsonWebKey, EllipticCurveJsonWebKey, or OctetJsonWebKey) based on the kty property.

public override Abblix.Jwt.JsonWebKey? Read(ref System.Text.Json.Utf8JsonReader reader, System.Type typeToConvert, System.Text.Json.JsonSerializerOptions options);

Parameters

reader System.Text.Json.Utf8JsonReader
typeToConvert System.Type
options System.Text.Json.JsonSerializerOptions

Returns

JsonWebKey

JsonWebKeyConverter.Write(Utf8JsonWriter, JsonWebKey, JsonSerializerOptions) Method

Writes a JsonWebKey to JSON in its concrete-subtype shape, so the resulting object includes the kty discriminator and every key-type-specific member.

public override void Write(System.Text.Json.Utf8JsonWriter writer, Abblix.Jwt.JsonWebKey value, System.Text.Json.JsonSerializerOptions options);

Parameters

writer System.Text.Json.Utf8JsonWriter
value JsonWebKey

options System.Text.Json.JsonSerializerOptions