Options

edit
OptionDefaultDescription
DefaultIgnoreConditionNeverCondition that skips members. See Members
IncludeFieldsfalseWrites the public fields
IncludeObsoleteMembersfalseWrites the members marked [Obsolete]
PropertyOrdernullComparer that sorts the members by name
DictionaryKeyOrdernullComparer that sorts the keys of dictionaries
MaxDepth64Maximum nesting depth of objects and collections
ShowInvisibleCharactersInValuesfalseMakes whitespace and control characters visible. See Output format
NewLine"\n"Line separator: "\n" or "\r\n"
ConvertersEmptyConverters that take precedence over the built-in ones. See Converters

The methods AddAttribute, AddPropertyAttribute, AddFieldAttribute, AddTypeAttribute, IgnoreMember, IgnoreMembersWithType and IgnoreMembersThatThrow configure members (Members), AddFormatter, AddJsonFormatter, AddXmlFormatter, AddUrlEncodedFormFormatter and AddHtmlFormatter configure formatters (JSON, XML and HTML values), and AddHttpConverters configures HTTP messages (HTTP messages).

HumanReadableSerializer.Serialize(value) without options uses a shared default instance.

Reuse and copy options

var options = new HumanReadableSerializerOptions { PropertyOrder = StringComparer.Ordinal };
_ = HumanReadableSerializer.Serialize(new { B = 1, A = 2 }, options);

// The options cannot change once they have been used...
Assert.True(options.IsReadOnly);
Assert.Throws<InvalidOperationException>(() => options.IncludeFields = true);

// ...but a copy can
var copy = options with { IncludeFields = true };
Assert.False(copy.IsReadOnly);
  • The options cache the converters and members of each type. Create an instance once and reuse it, for instance in a static field; an instance per call repeats the reflection work.
  • The first serialization makes the instance read-only (IsReadOnly): changing a property, adding a converter or an attribute then throws an InvalidOperationException. MakeReadOnly() does the same explicitly.
  • HumanReadableSerializerOptions is a record: options with { ... } creates a mutable copy, with the converters, attributes and formatters of the original, that you can change.
  • A read-only instance can be used by several threads at the same time.

Serialize as a type

Serialize(value, type, options) picks the converter of type instead of the converter of the runtime type of the value. The value must be assignable to the type, or an ArgumentException is thrown.