ktsu.JsonRequiredConditionally
A System.Text.Json attribute that makes a property required only when a sibling property has a given value, enforced during deserialization.
Introduction
ktsu.JsonRequiredConditionally fills a gap in System.Text.Json's built-in [JsonRequired]: a property that
is only mandatory under some condition, typically the value of a sibling discriminator property. Rather than
hand-rolling that check in a custom converter or in post-deserialization validation, decorate the member with
[JsonRequiredIfSiblingIs(nameof(Sibling), value)] and register one factory. The library walks the whole
materialized object graph — nested objects, arrays, and dictionaries — and reports every violation it finds in
a single exception, with a path to each one.
Features
- Conditional requirement:
[JsonRequiredIfSiblingIs(nameof(Sibling), value)] marks a member required
only when a sibling holds a specific value.
- OR within a sibling, AND across siblings: repeat the attribute with the same sibling name to accept
several qualifying values; use different sibling names to require all of several conditions at once.
- Presence-based, like
[JsonRequired]: for [JsonRequiredIfSiblingIs], a required property that
is physically present in the payload passes even when its value is null.
[JsonRequiredAndNotEmpty] is the one stated exception: it treats null, and other empty values, as
a violation. See Semantics and [JsonRequiredAndNotEmpty].
- Whole-graph validation: nested objects, arrays, and dictionaries are all walked, and every missing
property is reported together, not just the first.
- Path-qualified errors:
JsonRequiredConditionallyException.MissingProperties reports paths such as
Child.Tuning, Children[1].Tuning, and Lookup.a.Tuning, not bare member names.
- Drop-in converter factory: one line in
JsonSerializerOptions.Converters opts a whole object graph in;
types with no decorated members keep the serializer's normal fast path.
Installation
Package Manager Console
Install-Package ktsu.JsonRequiredConditionally
.NET CLI
dotnet add package ktsu.JsonRequiredConditionally
Package Reference
<PackageReference Include="ktsu.JsonRequiredConditionally" Version="x.y.z" />
Usage Examples
Basic Example
Decorate the conditionally-required member, then register the factory once:
using ktsu.JsonRequiredConditionally;
using System.Text.Json;
using System.Text.Json.Serialization;
public sealed class Config
{
public Kind Kind { get; set; }
[JsonRequiredIfSiblingIs(nameof(Kind), Kind.Advanced)]
public string? Tuning { get; set; }
}
JsonSerializerOptions options = new()
{
Converters =
{
// Needed only because this example writes Kind as a string ("Advanced"); it is not a
// requirement of JsonRequiredConditionally itself, which works with any converter setup.
new JsonStringEnumConverter(),
new JsonRequiredConditionallyConverterFactory(),
},
};
// throws JsonRequiredConditionallyException
JsonSerializer.Deserialize<Config>("""{"Kind":"Advanced"}""", options);
// succeeds
JsonSerializer.Deserialize<Config>("""{"Kind":"Basic"}""", options);
Combining Conditions
Attributes group implicitly by sibling name. Values within a group are OR-ed; the groups themselves
are AND-ed.
[JsonRequiredIfSiblingIs(nameof(Kind), Kind.Advanced)]
[JsonRequiredIfSiblingIs(nameof(Kind), Kind.Expert)]
[JsonRequiredIfSiblingIs(nameof(Mode), Mode.Remote)]
public string? Tuning { get; set; }
// required when (Kind is Advanced OR Expert) AND (Mode is Remote)
This is what makes the common case — one enum sibling with several qualifying values — expressible.
AND-ing those would be unsatisfiable, since Kind cannot be both Advanced and Expert.
Semantics
Presence satisfies the requirement, not non-nullness, for [JsonRequiredIfSiblingIs]. A required
property that is physically present passes even when its value is null. This mirrors how
[JsonRequired] itself behaves.
{ "Kind": "Advanced" } // absent -> throws
{ "Kind": "Advanced", "Tuning": null } // present -> passes
[JsonRequiredAndNotEmpty] is the one stated exception to this rule: it treats null, along with
other empty values, as a violation rather than as satisfying presence. See
[JsonRequiredAndNotEmpty] below.
Absent siblings read as their CLR default. Sibling values are read from the materialized object,
so a sibling missing from the payload reads as default. An enum sibling whose zero value is a
meaningful case is therefore matched by an absent sibling:
[JsonRequiredIfSiblingIs(nameof(Kind), Kind.Basic)] // Basic == 0
public string? Name { get; set; }
// {} -> Kind defaults to Basic, so Name is required
If you need to distinguish "absent" from "defaulted", mark the sibling [JsonRequired] or make it
nullable.
An unresolvable sibling name throws InvalidOperationException the first time the type is used.
A typo'd nameof target is a coding error, and failing loudly beats a rule that quietly never fires.
The attribute value is widened to the sibling's type before comparing. An attribute argument can
only be a compile-time constant, so it is routinely a different type from the sibling it is compared
against. [JsonRequiredIfSiblingIs(nameof(Count), 1)] matches a long, short, byte, uint or
nint sibling, and an enum sibling is matched by an int, by another enum with the same underlying
value, or by the enum member's own name written as a string:
[JsonRequiredIfSiblingIs(nameof(Kind), "Advanced")] // matches Kind == Kind.Advanced
A float and a double are compared at float precision, whichever of the two is the constant:
0.1f against a double sibling matches a payload 0.1, and so does 0.1 against a float sibling.
Only numbers widen to other numbers. Strings, bools and chars are never coerced in either direction:
a string sibling is compared ordinally against string constants only, a number is never formatted
into a string or parsed out of one to make it match, and 0/1 never match a bool sibling nor
65 a char one. A pairing that could never match throws
InvalidOperationException at first use, for the same reason an unresolvable sibling name does.
A sibling declared as object, JsonElement or JsonNode is rejected for any non-null value.
System.Text.Json materializes such a member as an uninterpreted JSON value, which never equals an
attribute constant, so the rule would compile and then never fire. Declare the sibling with a concrete
type (string, a number, or an enum) instead. A null value is still accepted.
A null value against a non-nullable value-type sibling is rejected too. An int, an enum or a
Guid is never null, so [JsonRequiredIfSiblingIs(nameof(Count), null)] on an int Count would never
fire. Declare the sibling as int? to require the member when the sibling is absent or null.
Members System.Text.Json would not populate are not validated below. A get-only property on a
struct is one of these: System.Text.Json uses a value type's implicit parameterless constructor
unless an explicit [JsonConstructor] says otherwise, so such a property keeps its default and the
JSON that would have fed it is discarded. Nothing beneath it is validated, because validating it would
report violations against a payload the serializer never applied.
All violations are reported together, with paths. JsonRequiredConditionallyException.MissingProperties
lists every property that was required but absent across the whole object graph, not just the first,
and each entry is a path rather than a bare name:
// { "Kind": "Advanced", "Child": { "Kind": "Advanced" } }
exception.MissingProperties // ["Tuning", "Child.Tuning"]
// arrays: "Children[1].Tuning"
// dicts: "Lookup.a.Tuning"
A walk can produce two categories of violation, not one. MissingProperties covers absence, and
EmptyProperties covers a property that was present but carried an empty value under
[JsonRequiredAndNotEmpty]. Both are collected across the whole graph in the same pass and a single
JsonRequiredConditionallyException reports whichever categories are non-empty. See
[JsonRequiredAndNotEmpty] below.
Serialization is not validated. Write is plain delegation. It can still throw, but only to refuse
a configuration this library cannot support: ReferenceHandler.Preserve (or a custom ReferenceHandler) and a type-level
[JsonObjectCreationHandling] are rejected on write as well as on read. See
Limitations.
[JsonRequiredAndNotEmpty]
[JsonRequiredIfSiblingIs] answers a presence question. [JsonRequiredAndNotEmpty] answers a
different one: the property was present, but was there anything in it. It widens this library's scope
from conditional presence to declarative requirement and emptiness validation over the same
System.Text.Json contract model, and it is unconditional: no sibling, no value to match, just present
and non-empty.
using ktsu.JsonRequiredConditionally;
using System.Text.Json;
public sealed class Config
{
[JsonRequiredAndNotEmpty]
public List<string> Tags { get; set; } = [];
}
JsonSerializerOptions options = new()
{
Converters = { new JsonRequiredConditionallyConverterFactory() },
};
// throws JsonRequiredConditionallyException: Tags is absent, reported in MissingProperties
JsonSerializer.Deserialize<Config>("""{}""", options);
// throws JsonRequiredConditionallyException: Tags is present but empty, reported in EmptyProperties
JsonSerializer.Deserialize<Config>("""{"Tags":[]}""", options);
// succeeds
JsonSerializer.Deserialize<Config>("""{"Tags":["a"]}""", options);
Semantics
A decorated member is satisfied when its JSON property is present and its value is non-empty:
| Payload |
Result |
| property absent |
violation, reported as missing |
null |
violation, reported as empty |
"" |
violation, reported as empty |
[] |
violation, reported as empty |
{} |
violation, reported as empty |
" " |
satisfied |
"x", [1], {"a":1} |
satisfied |
number, true, false |
satisfied, and always will be |
Whitespace is not empty. This follows the framework's own definition, under which a string is empty
when its length is zero. That diverges deliberately from
System.ComponentModel.DataAnnotations.RequiredAttribute, which treats a whitespace-only string as
absent. " " satisfies [JsonRequiredAndNotEmpty] and would not satisfy [Required].
EmptyProperties is where present-but-empty violations land. MissingProperties is where absent ones
land, including for members decorated with [JsonRequiredAndNotEmpty].
Pairing with [JsonRequired]
[JsonRequiredAndNotEmpty] is self-sufficient. An absent property already lands in
MissingProperties, so adding [JsonRequired] alongside it is redundant.
Pairing also costs diagnostics. The converter buffers the subtree and deserializes it through a
factory-free clone of your options before this library's own walk runs. System.Text.Json's own
required-property check happens during that inner deserialization, strictly before the walk, so on an
absent property the caller gets System.Text.Json's own JsonException instead of reaching the walk
that would have collected every other violation in the payload. One property is named, not the full
list.
There are two narrow reasons someone might still pair them, and neither is a default:
[JsonRequiredAndNotEmpty] does nothing if the factory is not registered in
JsonSerializerOptions.Converters, whereas [JsonRequired] is enforced by the serializer regardless.
[JsonRequired] sets JsonPropertyInfo.IsRequired, which schema and OpenAPI generators read.
[JsonRequiredAndNotEmpty] is invisible to them.
[MinLength(1)] as an alternative
System.ComponentModel.DataAnnotations.MinLengthAttribute looks like the obvious alternative. It
applies to collections and strings and expresses emptiness directly. Three blockers were measured, not
assumed:
- Non-public members are invisible to it.
Validator.TryValidateObject reads properties through
TypeDescriptor, which yields public properties only. Internal or private members carrying
[JsonInclude], a common pattern for non-public DTOs, produced no validation results at all.
- It does not recurse. A holder containing an invalid child was reported valid. Reaching the
child means hand-writing the walk and the path reporting
GraphValidator already does.
[Required] is non-null, not non-empty, for anything that is not a System.String. A record
type wrapping "" passed, because RequiredAttribute only special-cases System.String itself,
and semantic string types are routinely records.
None of this makes DataAnnotations a bad choice in general. It simply cannot see what this library
sees: non-public members behind [JsonInclude], nested graphs, and values whose emptiness is only
answerable from the JSON payload itself.
Supported Frameworks
net10.0, net9.0, net8.0, net7.0, netstandard2.0