CrystalJsonSettings
Namespace: SnowBank.Data.Json · class
Implements: IEquatable<CrystalJsonSettings>
JSON serialization settings
Remarks
Instances of this type are immutable and can be cached
Constructors
CrystalJsonSettings
CrystalJsonSettings()
Properties
AllowTrailingData
bool AllowTrailingData { get; }
Specifies whether extra non-whitespace content after the top-level JSON value is tolerated while parsing.
By default (false), any content following the first complete value (a second document, or trailing garbage) is a syntax error.
Enable this (via WithTrailingData) to parse only the first value and ignore the rest. To consume consecutive fragments from a buffer, prefer ParseFragment or the streaming reader instead. This only impacts deserialization.
DataContractCompat
static CrystalJsonSettings DataContractCompat { get; }
Serialize the COMPLETE legacy output of DataContractJsonSerializer: numeric enums, \/Date(...)\/ dates, ISO 8601 duration strings for TimeSpan, dictionaries as [{"Key":..,"Value":..}] pair arrays, and explicit null members
Equivalent to CrystalJsonSettings.Json.WithEnumAsNumbers().WithMicrosoftDates().WithIso8601Durations().WithDictionariesAsPairArrays().WithNullMembers(), as one named, cached preset.
This preset reproduces every DCJS output construct that has a settings-level recipe, so an endpoint using it feeds an unchanged legacy reader without any per-construct configuration.
Scope it to the endpoints that feed an unchanged legacy reader: WithNullMembers in particular is pure verbosity for every consumer that is not a frozen legacy reader.
Reading never needs this preset: the legacy date, duration and dictionary shapes, and numbers or numeric strings for enums, are all accepted on read by default.
DateFormatting
DateFormat DateFormatting { get; }
Rules for serialization of dates and times
DenyComments
bool DenyComments { get; }
Specifies whether JavaScript-style comments (// ... and /* ... */) are rejected while parsing.
By default (false), comments are allowed and silently skipped.
Comments are a non-standard extension: enable this setting (via WithoutComments or the JsonStrict preset) to reject them with a syntax error. This only impacts deserialization.
DenyTrailingCommas
bool DenyTrailingCommas { get; }
If true, reject any trailing ',' at the end of an array or object.
By default (false), all trailing commas are silently ignored.
The official specification does not allow trailing commas, and compliant parsers will throw a syntax error. Enable this setting to replicate the same behavior.
This only impacts deserialization. The serializer will never output a trailing commas when generation JSON text documents.
DictionariesAsPairArrays
bool DictionariesAsPairArrays { get; }
Tests if dictionaries are serialized as an array of { "Key": ..., "Value": ... } objects (the legacy DataContractJsonSerializer output shape) instead of a JSON object map
This only affects serialization: on read, both shapes are always accepted.
DoNotTrackVisitedObjects
bool DoNotTrackVisitedObjects { get; }
If true, do not track the graph of visited objects, and disable any protection against cyclic references
CAUTION: Attempting to serialize an object that contains cyclic references will either throw a or an , which may destabilize the system!
EnumsAsString
bool EnumsAsString { get; }
If true (the default), serialize all enum types as a string. If false serialize them as a number
The string form uses the custom output tokens declared on the enum's fields when present, otherwise the equivalent of ToString; the casing is controlled by UseCamelCasingForEnums.
Reading is always tolerant of both forms (names and tokens case-insensitively, numbers, and numeric strings), so this setting only affects what is written.
Flags
OptionFlags Flags { get; }
Flags corresponding to the serialization rules that will be used
FloatFormatting
FloatFormat FloatFormatting { get; }
Rules for serializing special floating point numbers, like NaN or PositiveInfinity
HideClassId
bool HideClassId { get; }
If true, do not include the "_class" field in generated JSON objects
This may have an impact when attempting to deserialized abstract classes or interfaces.
Please note that the content of the _class field has meaning only for compatible .NET applications, and should only be used in a "closed" ecosystem where all parties that have to serialize/deserialize abstract JSON objects use the same type names for the same objects!
HideDefaultValues
bool HideDefaultValues { get; }
If true, omit all fields that are equal to the default value of their type, including null, 0, false, DateTime.MinValue, etc...
By default, all Value Types will be serialized, and only Ref Types or Nullable are omitted (unless ShowNullMembers is set)
IgnoreCaseForNames
bool IgnoreCaseForNames { get; }
If true, ignore the case of field names during parsing (ex: "userId", "UserId", "USERID" will be considered the same field)
InterningMode
StringInterning InterningMode { get; }
Rules for interning of strings (when parsing JSON documents)
IsCanonicalOutput
bool IsCanonicalOutput { get; }
Output is canonical: object members are sorted by ordinal comparison of their name (attribute-driven ordering is disregarded), and numbers are rendered from their value (the source literal only decides the int/float shape).
Iso8601Durations
bool Iso8601Durations { get; }
Serialize TimeSpan values as ISO 8601 duration strings ("P1DT2H3M4.005S") instead of a number of seconds
JavaScript
static CrystalJsonSettings JavaScript { get; }
Parse or serialize JavaScript objects, with minimum formatting
This will produce a single line, but keep spaces between items: { hello: 'world', foo: [ 1, 2, 3 ] }
JavaScriptCompact
static CrystalJsonSettings JavaScriptCompact { get; }
Serialize Javascript into the most compact possible form
This will remove all extra white spaces and new lines: {hello:'world',foo:[1,2,3]}
JavaScriptIgnoreCase
static CrystalJsonSettings JavaScriptIgnoreCase { get; }
Parse JSON values, with case-insensitive field names in objects
These three forms are all equivalent: { hello: 'world'} == { HELLO: 'world' } == { HeLLo: "world" }
The casing of the field names will be the same as the original. In case of duplicate keys with different case, the last value will be used, but the casing of the key will be unspecified
JavaScriptIndented
static CrystalJsonSettings JavaScriptIndented { get; }
Serialize JavaScript into a form readable by humans
This will produce an indented multi-line output, suitable for log files or debug consoles: { hello: 'world', foo: [ 1, 2, 3 ] }
JavaScriptReadOnly
static CrystalJsonSettings JavaScriptReadOnly { get; }
Parse JavaScript read-only immutable values
Any object or array will be read-only and immutable. As such, they can be safely shared, cached, or used as a singleton.
If you need to modify the parsed result, either use a non-readonly variant, or create a new mutable copy.
JavaScriptReadOnlyIgnoreCase
static CrystalJsonSettings JavaScriptReadOnlyIgnoreCase { get; }
Parse JavaScript read-only immutable values, with case-insensitive field names in objects
These three forms are all equivalent: { hello: 'world' } == { HELLO: 'world' } == { HeLLo: 'world' }
The casing of the field names will be the same as the original. In case of duplicate keys with different case, the last value will be used, but the casing of the key will be unspecified
Any object or array will be read-only and immutable. As such, they can be safely shared, cached, or used as a singleton.
If you need to modify the parsed result, either use a non-readonly variant, or create a new mutable copy.
Json
static CrystalJsonSettings Json { get; }
Parse or serialize JSON, with only minimum formatting
This will produce a single line, but keep spaces between items: { "hello": "world", "foo": [ 1, 2, 3 ] }
JsonCompact
static CrystalJsonSettings JsonCompact { get; }
Serialize JSON into the most compact possible form
This will remove all extra white spaces and new lines: {"hello":"world","foo":[1,2,3]}
JsonIgnoreCase
static CrystalJsonSettings JsonIgnoreCase { get; }
Parse JSON values, with case-insensitive field names in objects
These three forms are all equivalent: { "hello": "world" } == { "HELLO": "world" } == { "HeLLo": "world" }
The casing of the field names will be the same as the original. In case of duplicate keys with different case, the last value will be used, but the casing of the key will be unspecified
JsonIndented
static CrystalJsonSettings JsonIndented { get; }
Serialize JSON into a form readable by humans
This will produce an indented multi-line output, suitable for log files or debug consoles: { "hello": "world", "foo": [ 1, 2, 3 ] }
JsonReadOnly
static CrystalJsonSettings JsonReadOnly { get; }
Parse JSON read-only immutable values
Any object or array will be read-only and immutable. As such, they can be safely shared, cached, or used as a singleton.
If you need to modify the parsed result, either use a non-readonly variant, or create a new mutable copy.
JsonReadOnlyIgnoreCase
static CrystalJsonSettings JsonReadOnlyIgnoreCase { get; }
Parse JSON read-only immutable values, with case-insensitive field names in JSON objects
These three forms are all equivalent: { "hello": "world" } == { "HELLO": "world" } == { "HeLLo": "world" }
The casing of the field names will be the same as the original. In case of duplicate keys with different case, the last value will be used, but the casing of the key will be unspecified
Any object or array will be read-only and immutable. As such, they can be safely shared, cached, or used as a singleton.
If you need to modify the parsed result, either use a non-readonly variant, or create a new mutable copy.
JsonStrict
static CrystalJsonSettings JsonStrict { get; }
Parse JSON using strict rules (no support for trailing commas, comments, ...)
OptimizeForLargeData
bool OptimizeForLargeData { get; }
If true, expect the generated JSON to be large, and pre-allocated large buffers. If false, expect the JSON to be small and do not pre-allocated buffers
Can have an impact on the memory footprint and memory allocations/copies.
OverwriteDuplicateFields
bool OverwriteDuplicateFields { get; }
If true, overwrite any duplicate field in an object, by keeping only the last value. If false, throws an exception in case of duplicates
Please note that is IgnoreCaseForNames is set, this will also include casing (ex: "userId" and "UserId" would be considered duplicates)
ReadOnly
bool ReadOnly { get; }
If true, parsed JSON documents will be read-only. If false, they will be mutable by default.
Parsed read-only documents will be immutable, and can be safely cached, shared or used as singleton. Mutable documents can be modified, but may require deep copy to prevent side effects.
This setting as no effect when serializing.
ShowNullMembers
bool ShowNullMembers { get; }
If true, outputs all fields of an object, including all fields that are null.
By default, all null fields are omitted, to reduce the size of the generated JSON document.
This setting is ignored if HideDefaultValues is used.
TargetLanguage
Target TargetLanguage { get; }
Target language (JSON, JavaScript, ...)
TextLayout
Layout TextLayout { get; }
Rules for spacing and indentation
UseCamelCasingForEnums
bool UseCamelCasingForEnums { get; }
If true, convert all enum string literal to camelCasing (ex: "someValue"). If false, use the same casing as used in the C# source code.
UseCamelCasingForNames
bool UseCamelCasingForNames { get; }
If true, convert all field names to use camelCasing (ex: "userId", "familyName", ...)
Methods
CamelCased
CrystalJsonSettings CamelCased()
Serialize all field names using camelCase ("firstName", like JavaScript)
Canonical
CrystalJsonSettings Canonical()
Enables canonical output: within a compatible range of library versions, the same JSON DOM serialized with the same settings produces the same text, and the output is closed under reparse. A runtime change or a required bug fix may still change the output between versions; such changes are called out in the release notes. Not supported on the netstandard2.0/net472 build (no shortest-round-trip float formatting there).
A DateTime of Local renders with the machine's current UTC offset, so the canonical bytes for a local time differ across machines and across a DST change on the same machine. Use UTC times when hashing or comparing canonical output across nodes.
A Single (Single) member widens to Double before rendering, and the output carries the double's digits, not the float's: 0.1f renders as 0.10000000149011612.
A Decimal beyond double precision still serializes deterministically, but reparses as a Double. Closure under reparse (same DOM in, same DOM out) holds only for decimal values that are exactly representable as a double.
Combining Canonical with the JavaScript target (JavaScript) is not supported: the JavaScript target emits non-JSON string quoting.
Compacted
CrystalJsonSettings Compacted()
The generated JSON will be single-line and without any spacing between items and fields.
DisableInterning
CrystalJsonSettings DisableInterning()
Disable any form of string interning
Equals
bool Equals(object obj)
bool Equals(CrystalJsonSettings other)
ExpectLargeData
CrystalJsonSettings ExpectLargeData()
Optimize memory allocations for a large JSON document
FlattenDuplicateFields
CrystalJsonSettings FlattenDuplicateFields()
If an object has duplicate field names, only the last value will be kept (default)
ForJavaScript
CrystalJsonSettings ForJavaScript()
Generate a native Javascript object or array: { hello: 'world', items: [ 1, 2, 3 ] }
Formatted
CrystalJsonSettings Formatted()
The generated JSON will be single-line, but with spacing between items and fields.
GetHashCode
int GetHashCode()
Indented
CrystalJsonSettings Indented()
The generated JSON will be multi-line and with indentation.
NotCanonical
CrystalJsonSettings NotCanonical()
Disables canonical output
OptimizedFor
CrystalJsonSettings OptimizedFor(bool largeData)
Optimize memory allocations depending on the expected size of the generated JSON document
PascalCased
CrystalJsonSettings PascalCased()
Serialize all field names using the same literal as in the original C# source code (which traditionally is using PascalCasing)
If the original source code use a different casing, then this will be used without any change.
ThrowOnDuplicateFields
CrystalJsonSettings ThrowOnDuplicateFields()
If an object has duplicate field names, an error will be thrown
ToString
string ToString()
WithCaseOnFields
CrystalJsonSettings WithCaseOnFields(bool ignoreCase = false)
Treat all field names as case-sensitive (by default)
This setting has no effect when serializing to JSON.
WithClassId
CrystalJsonSettings WithClassId(bool enabled = false)
Specify whether the _class field should be included or not in the generated JSON
WithComments
CrystalJsonSettings WithComments()
Allow JavaScript-style comments (// ... and /* ... */) inside parsed JSON documents (default)
Comments are a non-standard extension; this setting has no effect when serializing to JSON.
WithDateFormat
CrystalJsonSettings WithDateFormat(DateFormat format)
Specify the format used to serialized dates and times
WithDefaultValues
CrystalJsonSettings WithDefaultValues(bool show = false)
Default values for value types members will be included.
WithDictionariesAsMaps
CrystalJsonSettings WithDictionariesAsMaps()
Serialize dictionaries as a JSON object map (the default)
WithDictionariesAsPairArrays
CrystalJsonSettings WithDictionariesAsPairArrays()
Serialize dictionaries as an array of { "Key": ..., "Value": ... } objects, the output shape produced by the legacy DataContractJsonSerializer
Only for interoperability with clients that cannot read a JSON object map; the shape is also always accepted on read, without this setting.
WithEnumAsNumbers
CrystalJsonSettings WithEnumAsNumbers()
Serialize all enums as numbers (the default is their string literal)
WithEnumAsStrings
CrystalJsonSettings WithEnumAsStrings()
Serialize all enums as string literals (the default)
CrystalJsonSettings WithEnumAsStrings(bool camelCased)
Specify the way field names should be serialized
camelCased— Iftrue, using camelCasing. Iffalse, use the same literal as in the original source code
WithFloatFormat
CrystalJsonSettings WithFloatFormat(FloatFormat format)
Specify the wait special floating point numbers are serialized (NaN, PositiveInfinity, NegativeInfinity, ...)
WithInterning
CrystalJsonSettings WithInterning(StringInterning mode)
Specify the way strings should be interned when parsing documents
WithIso8601Dates
CrystalJsonSettings WithIso8601Dates()
Serialize dates using the ISO 8601 format: "YYYY-MM-DDTHH:mm:ss.ffff+TZ"
WithIso8601Durations
CrystalJsonSettings WithIso8601Durations()
Serialize TimeSpan values as ISO 8601 duration strings ("P1DT2H3M4.005S"), the output form produced by the legacy DataContractJsonSerializer
Only for interoperability with legacy readers; the form is also always accepted on read, without this setting.
WithJavaScriptDates
CrystalJsonSettings WithJavaScriptDates()
Serialize dates using the Javascript notation: new Date(xxxx)
WithMicrosoftDates
CrystalJsonSettings WithMicrosoftDates()
Serialize dates using the Microsoft notation: "\/Date(xxxxx)\/"
WithNullMembers
CrystalJsonSettings WithNullMembers()
Null values for members (ref types and Nullable) will be included.
WithNumericDurations
CrystalJsonSettings WithNumericDurations()
Serialize TimeSpan values as a number of seconds (the default)
WithObjectTracking
CrystalJsonSettings WithObjectTracking(bool enabled = false)
Specify whether to track visited objects, and protect against cyclic references
WithTextLayout
CrystalJsonSettings WithTextLayout(Layout layout)
WithTrailingCommas
CrystalJsonSettings WithTrailingCommas()
Allow trailing commas at the end of objects or arrays (by default)
This setting has no effect when serializing to JSON.
WithTrailingData
CrystalJsonSettings WithTrailingData()
Tolerate extra content after the top-level JSON value (parse only the first value and ignore the rest)
To consume consecutive fragments from a buffer, prefer or the streaming reader.
WithoutCaseOnFields
CrystalJsonSettings WithoutCaseOnFields()
Treat all field names as case-insensitive
This setting has no effect when serializing to JSON.
WithoutClassId
CrystalJsonSettings WithoutClassId()
Do not include the _class field in the generated JSON
WithoutComments
CrystalJsonSettings WithoutComments()
Reject JavaScript-style comments (// ... and /* ... */), which will be considered as syntax errors
WithoutDefaultValues
CrystalJsonSettings WithoutDefaultValues()
Default values for all members will be omitted
WithoutNullMembers
CrystalJsonSettings WithoutNullMembers()
Null values for members (ref types and Nullable) will be omitted.
WithoutObjectTracking
CrystalJsonSettings WithoutObjectTracking()
Disable tracking of visited objects, and inhibit any protection against cyclic references
This should be used with extreme caution, because it could lead to stack overflow or out of memory errors!
In some extreme circumstances, with a very large and deep object tree, this can give more performances, but should only be used when the constructed document is an acyclic graph.
WithoutTrailingCommas
CrystalJsonSettings WithoutTrailingCommas()
Disallow trailing commas at the end of objects or arrays, which will be considered as syntax errors
WithoutTrailingData
CrystalJsonSettings WithoutTrailingData()
Reject any content after the top-level JSON value as a syntax error (default)