JsonBooleanLiteralsAttribute

Namespace: SnowBank.Data.Json · class

Implements: Attribute

Specifies custom output literals for a Boolean (or bool?) member, for compatibility with producers that do not emit real JSON booleans

Remarks

Example: [JsonBooleanLiterals("0", "1")] serializes false as "0" and true as "1"; the int flavor [JsonBooleanLiterals(0, 1)] emits JSON numbers instead of strings.

Reading is tolerant by default: the configured literals are accepted (case-insensitively for strings) and genuine true/false as well, so the day the producer is modernized to emit real booleans, no redeploy is needed. Set StrictLiterals to true to reject genuine booleans instead, when catching a silently-changed producer matters more than tolerance.

There is no System.Text.Json equivalent: STJ's answer for this shape is a custom converter. This attribute exists so a migrating application does not have to write one per member.

Constructors

JsonBooleanLiteralsAttribute

JsonBooleanLiteralsAttribute(object whenFalse, object whenTrue)

Specifies the output literals for this member

  • whenFalse — Output form of false: a String, a Boolean, or a numeric value (ex: "0", 0). Pass null to NOT EMIT the member at all when the value is false, for a consumer that expects either the member absent or the true literal.
  • whenTrue — Output form of true: a String, a Boolean, or a numeric value (ex: "1", 1). It may not be null: emitting nothing for true has no meaning.

The two arguments do not have to share a type: [JsonBooleanLiterals("0", 1)] is legal, because legacy outputs are not always consistent.

Properties

FalseLiteral

JsonValue FalseLiteral { get; }

Output form of false, or null when the member is not emitted at all for false

StrictLiterals

bool StrictLiterals { get; set; }

When true, genuine JSON true/false are rejected on read instead of being accepted alongside the configured literals

TrueLiteral

JsonValue TrueLiteral { get; }

Output form of true