Class MessagePackSerializer
- Namespace
- Nerdbank.MessagePack
- Assembly
- Nerdbank.MessagePack.dll
Serializes .NET objects using the MessagePack format.
public record MessagePackSerializer : IEquatable<MessagePackSerializer>
- Inheritance
-
MessagePackSerializer
- Implements
- Inherited Members
Remarks
This type is immutable and thread-safe.
Changes to properties on this object should be performed with the record syntax with keyword.
Properties
ConverterFactories
Gets an array of converter factories to consult when creating a converter for a given type.
public ImmutableArray<IMessagePackConverterFactory> ConverterFactories { get; init; }
Property Value
Remarks
Factories are the last resort for creating a custom converter, coming after Nerdbank.MessagePack.SerializerConfiguration.Converters and Nerdbank.MessagePack.SerializerConfiguration.ConverterTypes.
ConverterTypes
Gets a collection of MessagePackConverter<T> types that should be used for their designated data types.
public ConverterTypeCollection ConverterTypes { get; init; }
Property Value
Remarks
The types in this collection are searched after matching Nerdbank.MessagePack.SerializerConfiguration.Converters and before Nerdbank.MessagePack.SerializerConfiguration.ConverterFactories when creating a converter for a given type.
Converters
Gets an array of MessagePackConverter<T> objects that should be used for their designated data types.
public ConverterCollection Converters { get; init; }
Property Value
Remarks
Converters in this collection are searched first when creating a converter for a given type, before Nerdbank.MessagePack.SerializerConfiguration.ConverterTypes and Nerdbank.MessagePack.SerializerConfiguration.ConverterFactories.
DerivedTypeMappings
Gets an array of DerivedShapeMapping<TBase> objects that add runtime insight into what derived types may appear in the serialized data for a given base type.
public DerivedTypeMappingCollection DerivedTypeMappings { get; init; }
Property Value
InternStrings
Gets a value indicating whether to intern strings during deserialization.
public bool InternStrings { get; init; }
Property Value
Remarks
String interning means that a string that appears multiple times (within a single deserialization or across many) in the msgpack data will be deserialized as the same string instance, reducing GC pressure.
When enabled, all deserialized are retained with a weak reference, allowing them to be garbage collected while also being reusable for future deserializations as long as they are in memory.
This feature has a positive impact on memory usage but may have a negative impact on performance due to searching through previously deserialized strings to find a match. If your application is performance sensitive, you should measure the impact of this feature on your application.
This feature is orthogonal and complementary to Nerdbank.MessagePack.SerializerConfiguration.PreserveReferences. Preserving references impacts the serialized result and can hurt interoperability if the other party is not using the same feature. Preserving references also does not guarantee that equal strings will be reused because the original serialization may have had multiple string objects for the same value, so deserialization would produce the same result. Preserving references alone will never reuse strings across top-level deserialization operations either. Interning strings however, has no impact on the serialized result and is always safe to use. Interning strings will guarantee string objects are reused within and across deserialization operations so long as their values are equal. The combination of the two features will ensure the most compact msgpack, and will produce faster deserialization times than string interning alone. Combining the two features also activates special behavior to ensure that serialization only writes a string once and references that string later in that same serialization, even if the equal strings were unique objects.
LibraryExtensionTypeCodes
Gets the extension type codes to use for library-reserved extension types.
public LibraryReservedMessagePackExtensionTypeCode LibraryExtensionTypeCodes { get; init; }
Property Value
Remarks
This property may be used to reassign the extension type codes for library-provided extension types in order to avoid conflicts with other libraries the application is using.
MaxAsyncBuffer
Gets the maximum length of msgpack to buffer before beginning deserialization.
public int MaxAsyncBuffer { get; init; }
Property Value
- int
May be set to any non-negative integer. The default value is 1MB and is subject to change.
Remarks
Larger values are more likely to lead to async buffering followed by synchronous deserialization, which is significantly faster than async deserialization. Smaller values are useful for limiting memory usage since deserialization can happen while pulling in more msgpack bytes, allowing release of the buffers containing earlier bytes to make room for subsequent ones.
This value has no impact once deserialization has begun. The msgpack structure to be deserialized and converters used during deserialization may result in buffering any amount of msgpack beyond this value.
MultiDimensionalArrayFormat
Gets the format to use when serializing multi-dimensional arrays.
public MultiDimensionalArrayFormat MultiDimensionalArrayFormat { get; init; }
Property Value
PerfOverSchemaStability
Gets a value indicating whether to boost performance using methods that may compromise the stability of the serialized schema.
public bool PerfOverSchemaStability { get; init; }
Property Value
Remarks
This setting is intended for use in performance-sensitive scenarios where the serialized data will not be stored or shared with other systems, but rather is used in a single system live data such that the schema need not be stable between versions of the application.
Examples of behavioral changes that may occur when this setting is true:
- All objects are serialized with an array of their values instead of maps that include their property names.
- Polymorphic type identifiers are always integers.
In particular, the schema is liable to change when this property is true and:
- Serialized members are added, removed or reordered within their declaring type.
- A DerivedTypeShapeAttribute is removed, or inserted before the last such attribute on a given type.
Changing this property (either direction) is itself liable to alter the schema of the serialized data.
Performance and schema stability can both be achieved at once by:
- Using the KeyAttribute on all serialized properties.
- Specifying Tag explicitly for all polymorphic types.
PreserveReferences
Gets a setting that determines how references to objects are preserved during serialization and deserialization.
public ReferencePreservationMode PreserveReferences { get; init; }
Property Value
- ReferencePreservationMode
The default value is Off because it requires no msgpack extensions, is compatible with all msgpack readers, adds no security considerations and is the most performant.
PropertyNamingPolicy
Gets the transformation function to apply to property names before serializing them.
public MessagePackNamingPolicy? PropertyNamingPolicy { get; init; }
Property Value
- MessagePackNamingPolicy
The default value is null, indicating that property names should be persisted exactly as they are declared in .NET.
SerializeDefaultValues
Gets the policy concerning which properties to serialize though they are set to their default values.
public SerializeDefaultValuesPolicy SerializeDefaultValues { get; init; }
Property Value
- SerializeDefaultValuesPolicy
The default value is Required, meaning that only required properties or properties with non-default values will be serialized.
Remarks
By default, the serializer omits properties and fields that are set to their default values when serializing objects. This property can be used to override that behavior and serialize all properties and fields, regardless of their value.
Objects that are serialized as arrays (i.e. types that use KeyAttribute on their members), have a limited ability to omit default values because the order of the elements in the array is significant. See the KeyAttribute documentation for details.
Default values are assumed to be default(TPropertyType)
except where overridden, as follows:
- Primary constructor default parameter values. e.g.
record Person(int Age = 18)
- Properties or fields attributed with DefaultValueAttribute. e.g.
[DefaultValue(18)] internal int Age { get; set; } = 18;
SerializeEnumValuesByName
Gets a value indicating whether enum values will be serialized by name rather than by their numeric value.
public bool SerializeEnumValuesByName { get; init; }
Property Value
Remarks
Serializing by name is a best effort. Most enums do not define a name for every possible value, and flags enums may have complicated string representations when multiple named enum elements are combined to form a value. When a simple string cannot be constructed for a given value, the numeric form is used.
When deserializing enums by name, name matching is case insensitive unless the enum type defines multiple values with names that are only distinguished by case.
StartingContext
Gets the starting context to begin (de)serializations with.
public SerializationContext StartingContext { get; init; }
Property Value
Methods
ConvertToJson(ref MessagePackReader, TextWriter, JsonOptions?)
Converts one MessagePack structure to a JSON stream.
public static void ConvertToJson(ref MessagePackReader reader, TextWriter jsonWriter, MessagePackSerializer.JsonOptions? options = null)
Parameters
reader
MessagePackReaderA reader of the msgpack stream.
jsonWriter
TextWriterThe writer that will receive JSON text.
options
MessagePackSerializer.JsonOptions?Options to customize how the JSON is written.
ConvertToJson(in ReadOnlySequence<byte>, JsonOptions?)
Converts a msgpack sequence into equivalent JSON.
public static string ConvertToJson(in ReadOnlySequence<byte> msgpack, MessagePackSerializer.JsonOptions? options = null)
Parameters
msgpack
ReadOnlySequence<byte>The msgpack sequence.
options
MessagePackSerializer.JsonOptions?- Options to customize how the JSON is written.
Returns
- string
The JSON.
Remarks
Not all valid msgpack can be converted to JSON. For example, msgpack maps with non-string keys cannot be represented in JSON. As such, this method is intended for debugging purposes rather than for production use.
ConvertToJson(ReadOnlyMemory<byte>, JsonOptions?)
Converts a msgpack sequence into equivalent JSON.
public static string ConvertToJson(ReadOnlyMemory<byte> msgpack, MessagePackSerializer.JsonOptions? options = null)
Parameters
msgpack
ReadOnlyMemory<byte>The msgpack sequence.
options
MessagePackSerializer.JsonOptions?- Options to customize how the JSON is written.
Returns
- string
The JSON.
Remarks
Not all valid msgpack can be converted to JSON. For example, msgpack maps with non-string keys cannot be represented in JSON. As such, this method is intended for debugging purposes rather than for production use.
CreateSerializationContext(ITypeShapeProvider, CancellationToken)
Creates a new serialization context that is ready to process a serialization job.
protected MessagePackSerializer.DisposableSerializationContext CreateSerializationContext(ITypeShapeProvider provider, CancellationToken cancellationToken = default)
Parameters
provider
ITypeShapeProvider-
The shape provider of
T
. This will typically be obtained by calling theShapeProvider
static property on a witness class (a class on which GenerateShapeAttribute<T> has been applied). cancellationToken
CancellationTokenA cancellation token for the operation.
Returns
- MessagePackSerializer.DisposableSerializationContext
The serialization context.
Remarks
Callers should be sure to always call Dispose() when done with the context.
DeserializeAsync<T>(PipeReader, CancellationToken)
Deserializes a value from a PipeReader.
public ValueTask<T?> DeserializeAsync<T>(PipeReader reader, CancellationToken cancellationToken = default) where T : IShapeable<T>
Parameters
reader
PipeReaderThe reader to deserialize from. Complete(Exception) is not called on this at the conclusion of deserialization, and the reader is left at the position after the last msgpack byte read.
cancellationToken
CancellationTokenA cancellation token.
Returns
- ValueTask<T>
The deserialized value.
Type Parameters
T
The type of value to deserialize.
DeserializeAsync<T>(Stream, CancellationToken)
Deserializes a value from a Stream.
public ValueTask<T?> DeserializeAsync<T>(Stream stream, CancellationToken cancellationToken = default) where T : IShapeable<T>
Parameters
stream
StreamThe stream to deserialize from. If this stream contains more than one top-level msgpack structure, it may be positioned beyond its end after deserialization due to buffering.
cancellationToken
CancellationToken- A cancellation token.
Returns
- ValueTask<T>
The deserialized value.
Type Parameters
T
The type to be serialized.
DeserializeAsync<T, TProvider>(PipeReader, CancellationToken)
Deserializes a value from a PipeReader.
public ValueTask<T?> DeserializeAsync<T, TProvider>(PipeReader reader, CancellationToken cancellationToken = default) where TProvider : IShapeable<T>
Parameters
reader
PipeReaderThe reader to deserialize from. Complete(Exception) is not called on this at the conclusion of deserialization, and the reader is left at the position after the last msgpack byte read.
cancellationToken
CancellationTokenA cancellation token.
Returns
- ValueTask<T>
The deserialized value.
Type Parameters
T
The type of value to deserialize.
TProvider
DeserializeAsync<T, TProvider>(Stream, CancellationToken)
Deserializes a value from a Stream.
public ValueTask<T?> DeserializeAsync<T, TProvider>(Stream stream, CancellationToken cancellationToken = default) where TProvider : IShapeable<T>
Parameters
stream
StreamThe stream to deserialize from. If this stream contains more than one top-level msgpack structure, it may be positioned beyond its end after deserialization due to buffering.
cancellationToken
CancellationToken- A cancellation token.
Returns
- ValueTask<T>
The deserialized value.
Type Parameters
T
The type to be serialized. TProvider
DeserializeDynamic(ref MessagePackReader, CancellationToken)
Deserializes msgpack into primitive values, maps and arrays.
public dynamic? DeserializeDynamic(ref MessagePackReader reader, CancellationToken cancellationToken = default)
Parameters
reader
MessagePackReaderThe source of msgpack to decode.
cancellationToken
CancellationTokenA cancellation token.
Returns
- dynamic
A null, string, long, ulong, float, double, DateTime, IReadOnlyDictionary<TKey, TValue> with object keys and values, an array of objects, or an Extension.
Examples
The following snippet demonstrates a way to use this method.
dynamic? deserialized = serializer.DeserializeDynamic(ref reader);
string prop1 = deserialized!.Prop1;
int prop2 = deserialized.Prop2;
bool deeperBool = deserialized.deeper.IsAdult;
int age = deserialized.People[3].Age;
// Did we miss anything? Dump out all the keys and their values.
foreach (object key in deserialized)
{
Console.WriteLine($"{key}: {deserialized[key]}");
}
Remarks
The resulting object is designed to work conveniently with the C# dynamic
type.
Maps become dynamic objects whose members are named after the keys in the maps. When maps do not use string keys, the values are still accessible by using the indexer on the object. Attempts to access values with keys that do not exist on the original msgpack object result in throwing a KeyNotFoundException. All members on maps are discoverable using foreach, which enumerates the keys on the object. Maps also implement IReadOnlyDictionary<TKey, TValue> with object keys and values.
Keep in mind when using integers that msgpack doesn't preserve integer length information. This method deserializes all integers as ulong (or long if the value is negative). Integer length stretching is automatically applied when using integers as keys in maps so that they can match.
All arrays are instances of object?[]
.
Msgpack binary data is represented as a byte[]
object.
Msgpack extensions are represented by Extension values.
DeserializeEnumerableAsync<T>(PipeReader, CancellationToken)
Deserializes a sequence of values such that each element is produced individually.
public IAsyncEnumerable<T?> DeserializeEnumerableAsync<T>(PipeReader reader, CancellationToken cancellationToken = default) where T : IShapeable<T>
Parameters
reader
PipeReaderThe reader to deserialize from. CompleteAsync(Exception) will be called only at the conclusion of a successful enumeration.
cancellationToken
CancellationTokenA cancellation token.
Returns
- IAsyncEnumerable<T>
An async enumerable, suitable for use with
await foreach
.
Type Parameters
T
The type of value to be deserialized.
Remarks
The content read from reader
must be a sequence of msgpack-encoded values with no envelope (e.g. an array).
After the reader
is exhausted, the sequence will end.
See DeserializeEnumerableAsync<T, TElement>(PipeReader, ITypeShapeProvider, StreamingEnumerationOptions<T, TElement>, CancellationToken) or any other overload that takes a MessagePackSerializer.StreamingEnumerationOptions<T, TElement> parameter for streaming a sequence of values that is nested within a larger msgpack structure.
Exceptions
- NotSupportedException
Thrown if PreserveReferences is not Off.
DeserializeEnumerableAsync<T>(Stream, CancellationToken)
public IAsyncEnumerable<T?> DeserializeEnumerableAsync<T>(Stream stream, CancellationToken cancellationToken = default) where T : IShapeable<T>
Parameters
stream
StreamThe stream to deserialize from. If this stream contains more than one top-level msgpack structure, it may be positioned beyond its end after deserialization due to buffering.
cancellationToken
CancellationToken- A cancellation token.
Returns
- IAsyncEnumerable<T>
An async enumerable, suitable for use with await foreach
.
Type Parameters
T
The type of value to be deserialized.
Remarks
The content read from reader
must be a sequence of msgpack-encoded values with no envelope (e.g. an array).
After the reader
is exhausted, the sequence will end.
See DeserializeEnumerableAsync<T, TElement>(PipeReader, ITypeShapeProvider, StreamingEnumerationOptions<T, TElement>, CancellationToken) or any other overload that takes a MessagePackSerializer.StreamingEnumerationOptions<T, TElement> parameter for streaming a sequence of values that is nested within a larger msgpack structure.
DeserializeEnumerableAsync<T, TElement>(PipeReader, StreamingEnumerationOptions<T, TElement>, CancellationToken)
Deserializes a sequence of values in a larger msgpack structure such that each element is produced individually.
public IAsyncEnumerable<TElement?> DeserializeEnumerableAsync<T, TElement>(PipeReader reader, MessagePackSerializer.StreamingEnumerationOptions<T, TElement> options, CancellationToken cancellationToken = default) where T : IShapeable<T>
Parameters
reader
PipeReaderThe reader to deserialize from. CompleteAsync(Exception) will be called only at the conclusion of a successful enumeration.
options
MessagePackSerializer.StreamingEnumerationOptions<T, TElement>Options to apply to the streaming enumeration.
cancellationToken
CancellationTokenA cancellation token.
Returns
- IAsyncEnumerable<TElement>
An async enumerable, suitable for use with
await foreach
.
Type Parameters
T
The type that describes the top-level msgpack structure.
TElement
The type of element to be enumerated within the structure.
Remarks
The content read from reader
must be a sequence of msgpack-encoded values with no envelope (e.g. an array).
After the reader
is exhausted, the sequence will end.
See DeserializeEnumerableAsync<T>(PipeReader, ITypeShapeProvider, CancellationToken) or any other overload that does not take a MessagePackSerializer.StreamingEnumerationOptions<T, TElement> parameter for streaming a sequence of values that are each top-level structures in the stream (with no envelope).
Exceptions
- NotSupportedException
Thrown if PreserveReferences is not Off.
DeserializeEnumerableAsync<T, TProvider>(PipeReader, CancellationToken)
Deserializes a sequence of values such that each element is produced individually.
public IAsyncEnumerable<T?> DeserializeEnumerableAsync<T, TProvider>(PipeReader reader, CancellationToken cancellationToken = default) where TProvider : IShapeable<T>
Parameters
reader
PipeReaderThe reader to deserialize from. CompleteAsync(Exception) will be called only at the conclusion of a successful enumeration.
cancellationToken
CancellationTokenA cancellation token.
Returns
- IAsyncEnumerable<T>
An async enumerable, suitable for use with
await foreach
.
Type Parameters
T
The type of value to be deserialized.
TProvider
Remarks
The content read from reader
must be a sequence of msgpack-encoded values with no envelope (e.g. an array).
After the reader
is exhausted, the sequence will end.
See DeserializeEnumerableAsync<T, TElement>(PipeReader, ITypeShapeProvider, StreamingEnumerationOptions<T, TElement>, CancellationToken) or any other overload that takes a MessagePackSerializer.StreamingEnumerationOptions<T, TElement> parameter for streaming a sequence of values that is nested within a larger msgpack structure.
Exceptions
- NotSupportedException
Thrown if PreserveReferences is not Off.
DeserializeEnumerableAsync<T, TElement>(Stream, StreamingEnumerationOptions<T, TElement>, CancellationToken)
public IAsyncEnumerable<TElement?> DeserializeEnumerableAsync<T, TElement>(Stream stream, MessagePackSerializer.StreamingEnumerationOptions<T, TElement> options, CancellationToken cancellationToken = default) where T : IShapeable<T>
Parameters
stream
StreamThe stream to deserialize from. If this stream contains more than one top-level msgpack structure, it may be positioned beyond its end after deserialization due to buffering.
options
MessagePackSerializer.StreamingEnumerationOptions<T, TElement>- Options to apply to the streaming enumeration.
cancellationToken
CancellationToken- A cancellation token.
Returns
- IAsyncEnumerable<TElement>
An async enumerable, suitable for use with await foreach
.
Type Parameters
T
The type that describes the top-level msgpack structure. TElement
The type of element to be enumerated within the structure.
Remarks
The content read from reader
must be a sequence of msgpack-encoded values with no envelope (e.g. an array).
After the reader
is exhausted, the sequence will end.
See DeserializeEnumerableAsync<T>(PipeReader, ITypeShapeProvider, CancellationToken) or any other overload that does not take a MessagePackSerializer.StreamingEnumerationOptions<T, TElement> parameter for streaming a sequence of values that are each top-level structures in the stream (with no envelope).
DeserializeEnumerableAsync<T, TProvider>(Stream, CancellationToken)
public IAsyncEnumerable<T?> DeserializeEnumerableAsync<T, TProvider>(Stream stream, CancellationToken cancellationToken = default) where TProvider : IShapeable<T>
Parameters
stream
StreamThe stream to deserialize from. If this stream contains more than one top-level msgpack structure, it may be positioned beyond its end after deserialization due to buffering.
cancellationToken
CancellationToken- A cancellation token.
Returns
- IAsyncEnumerable<T>
An async enumerable, suitable for use with await foreach
.
Type Parameters
T
The type of value to be deserialized. TProvider
Remarks
The content read from reader
must be a sequence of msgpack-encoded values with no envelope (e.g. an array).
After the reader
is exhausted, the sequence will end.
See DeserializeEnumerableAsync<T, TElement>(PipeReader, ITypeShapeProvider, StreamingEnumerationOptions<T, TElement>, CancellationToken) or any other overload that takes a MessagePackSerializer.StreamingEnumerationOptions<T, TElement> parameter for streaming a sequence of values that is nested within a larger msgpack structure.
DeserializeEnumerableAsync<T, TElement, TProvider>(PipeReader, StreamingEnumerationOptions<T, TElement>, CancellationToken)
Deserializes a sequence of values in a larger msgpack structure such that each element is produced individually.
public IAsyncEnumerable<TElement?> DeserializeEnumerableAsync<T, TElement, TProvider>(PipeReader reader, MessagePackSerializer.StreamingEnumerationOptions<T, TElement> options, CancellationToken cancellationToken = default) where TProvider : IShapeable<T>
Parameters
reader
PipeReaderThe reader to deserialize from. CompleteAsync(Exception) will be called only at the conclusion of a successful enumeration.
options
MessagePackSerializer.StreamingEnumerationOptions<T, TElement>Options to apply to the streaming enumeration.
cancellationToken
CancellationTokenA cancellation token.
Returns
- IAsyncEnumerable<TElement>
An async enumerable, suitable for use with
await foreach
.
Type Parameters
T
The type that describes the top-level msgpack structure.
TElement
The type of element to be enumerated within the structure.
TProvider
Remarks
The content read from reader
must be a sequence of msgpack-encoded values with no envelope (e.g. an array).
After the reader
is exhausted, the sequence will end.
See DeserializeEnumerableAsync<T>(PipeReader, ITypeShapeProvider, CancellationToken) or any other overload that does not take a MessagePackSerializer.StreamingEnumerationOptions<T, TElement> parameter for streaming a sequence of values that are each top-level structures in the stream (with no envelope).
Exceptions
- NotSupportedException
Thrown if PreserveReferences is not Off.
DeserializeEnumerableAsync<T, TElement, TProvider>(Stream, StreamingEnumerationOptions<T, TElement>, CancellationToken)
public IAsyncEnumerable<TElement?> DeserializeEnumerableAsync<T, TElement, TProvider>(Stream stream, MessagePackSerializer.StreamingEnumerationOptions<T, TElement> options, CancellationToken cancellationToken = default) where TProvider : IShapeable<T>
Parameters
stream
StreamThe stream to deserialize from. If this stream contains more than one top-level msgpack structure, it may be positioned beyond its end after deserialization due to buffering.
options
MessagePackSerializer.StreamingEnumerationOptions<T, TElement>- Options to apply to the streaming enumeration.
cancellationToken
CancellationToken- A cancellation token.
Returns
- IAsyncEnumerable<TElement>
An async enumerable, suitable for use with await foreach
.
Type Parameters
T
The type that describes the top-level msgpack structure. TElement
The type of element to be enumerated within the structure. TProvider
Remarks
The content read from reader
must be a sequence of msgpack-encoded values with no envelope (e.g. an array).
After the reader
is exhausted, the sequence will end.
See DeserializeEnumerableAsync<T>(PipeReader, ITypeShapeProvider, CancellationToken) or any other overload that does not take a MessagePackSerializer.StreamingEnumerationOptions<T, TElement> parameter for streaming a sequence of values that are each top-level structures in the stream (with no envelope).
DeserializeObject(ref MessagePackReader, ITypeShape, CancellationToken)
Deserializes an untyped value.
public object? DeserializeObject(ref MessagePackReader reader, ITypeShape shape, CancellationToken cancellationToken = default)
Parameters
reader
MessagePackReaderThe msgpack reader to deserialize from.
shape
ITypeShapeThe shape of the value to deserialize.
cancellationToken
CancellationTokenA cancellation token.
Returns
- object
The deserialized value.
Examples
See the SerializeObject(ref MessagePackWriter, object?, ITypeShape, CancellationToken) method for an example of using this method.
Deserialize<T>(scoped in ReadOnlySequence<byte>, CancellationToken)
Deserializes a value.
public T? Deserialize<T>(scoped in ReadOnlySequence<byte> bytes, CancellationToken cancellationToken = default) where T : IShapeable<T>
Parameters
bytes
ReadOnlySequence<byte>cancellationToken
CancellationTokenA cancellation token.
Returns
- T
The deserialized value.
Type Parameters
T
The type of value to deserialize.
Deserialize<T>(Stream, CancellationToken)
Deserializes a value.
public T? Deserialize<T>(Stream stream, CancellationToken cancellationToken = default) where T : IShapeable<T>
Parameters
stream
StreamThe stream to deserialize from. If this stream contains more than one top-level msgpack structure, it may be positioned beyond its end after deserialization due to buffering.
cancellationToken
CancellationTokenA cancellation token.
Returns
- T
The deserialized value.
Type Parameters
T
The type of value to deserialize.
Remarks
The implementation of this method currently is to buffer the entire content of the stream
into memory before deserializing.
This is for simplicity and perf reasons.
Callers should only provide streams that are known to be small enough to fit in memory and contain only msgpack content.
Deserialize<T>(ReadOnlyMemory<byte>, CancellationToken)
Deserializes a value.
public T? Deserialize<T>(ReadOnlyMemory<byte> bytes, CancellationToken cancellationToken = default) where T : IShapeable<T>
Parameters
bytes
ReadOnlyMemory<byte>cancellationToken
CancellationTokenA cancellation token.
Returns
- T
The deserialized value.
Type Parameters
T
The type of value to deserialize.
Deserialize<T, TProvider>(scoped in ReadOnlySequence<byte>, CancellationToken)
Deserializes a value.
public T? Deserialize<T, TProvider>(scoped in ReadOnlySequence<byte> bytes, CancellationToken cancellationToken = default) where TProvider : IShapeable<T>
Parameters
bytes
ReadOnlySequence<byte>cancellationToken
CancellationTokenA cancellation token.
Returns
- T
The deserialized value.
Type Parameters
T
The type of value to deserialize.
TProvider
Deserialize<T, TProvider>(Stream, CancellationToken)
Deserializes a value.
public T? Deserialize<T, TProvider>(Stream stream, CancellationToken cancellationToken = default) where TProvider : IShapeable<T>
Parameters
stream
StreamThe stream to deserialize from. If this stream contains more than one top-level msgpack structure, it may be positioned beyond its end after deserialization due to buffering.
cancellationToken
CancellationTokenA cancellation token.
Returns
- T
The deserialized value.
Type Parameters
T
The type of value to deserialize.
TProvider
Remarks
The implementation of this method currently is to buffer the entire content of the stream
into memory before deserializing.
This is for simplicity and perf reasons.
Callers should only provide streams that are known to be small enough to fit in memory and contain only msgpack content.
Deserialize<T, TProvider>(ReadOnlyMemory<byte>, CancellationToken)
Deserializes a value.
public T? Deserialize<T, TProvider>(ReadOnlyMemory<byte> bytes, CancellationToken cancellationToken = default) where TProvider : IShapeable<T>
Parameters
bytes
ReadOnlyMemory<byte>cancellationToken
CancellationTokenA cancellation token.
Returns
- T
The deserialized value.
Type Parameters
T
The type of value to deserialize.
TProvider
GetJsonSchema(ITypeShape)
Creates a JSON Schema that describes the msgpack serialization of the given type's shape.
public JsonObject GetJsonSchema(ITypeShape typeShape)
Parameters
typeShape
ITypeShapeThe shape of the type.
Returns
- JsonObject
The JSON Schema document.
GetJsonSchema<T>()
public JsonObject GetJsonSchema<T>() where T : IShapeable<T>
Returns
- JsonObject
The JSON Schema document.
Type Parameters
T
The self-describing type whose schema should be produced.
GetJsonSchema<T>(ITypeShapeProvider)
public JsonObject GetJsonSchema<T>(ITypeShapeProvider provider)
Parameters
provider
ITypeShapeProvider-
The shape provider of
T
. This will typically be obtained by calling theShapeProvider
static property on a witness class (a class on which GenerateShapeAttribute<T> has been applied).
Returns
- JsonObject
The JSON Schema document.
Type Parameters
T
The type whose schema should be produced.
GetJsonSchema<T, TProvider>()
public JsonObject GetJsonSchema<T, TProvider>() where TProvider : IShapeable<T>
Returns
- JsonObject
The JSON Schema document.
Type Parameters
T
The type whose schema should be produced.
TProvider
The witness type that provides the shape for
T
.
SerializeAsync<T>(PipeWriter, in T?, CancellationToken)
Serializes a value using the given PipeWriter.
public ValueTask SerializeAsync<T>(PipeWriter writer, in T? value, CancellationToken cancellationToken = default) where T : IShapeable<T>
Parameters
writer
PipeWriterThe writer to use.
value
TThe value to serialize.
cancellationToken
CancellationTokenA cancellation token.
Returns
- ValueTask
A task that tracks the async serialization.
Type Parameters
T
The type to be serialized.
SerializeAsync<T>(Stream, in T?, CancellationToken)
Serializes a value to a Stream.
public ValueTask SerializeAsync<T>(Stream stream, in T? value, CancellationToken cancellationToken = default) where T : IShapeable<T>
Parameters
stream
StreamThe stream to write to.
value
T- The value to serialize.
cancellationToken
CancellationToken- A cancellation token.
Returns
- ValueTask
A task that tracks the async serialization.
Type Parameters
T
The type to be serialized.
SerializeAsync<T, TProvider>(PipeWriter, in T?, CancellationToken)
Serializes a value using the given PipeWriter.
public ValueTask SerializeAsync<T, TProvider>(PipeWriter writer, in T? value, CancellationToken cancellationToken = default) where TProvider : IShapeable<T>
Parameters
writer
PipeWriterThe writer to use.
value
TThe value to serialize.
cancellationToken
CancellationTokenA cancellation token.
Returns
- ValueTask
A task that tracks the async serialization.
Type Parameters
T
The type to be serialized.
TProvider
SerializeAsync<T, TProvider>(Stream, in T?, CancellationToken)
Serializes a value to a Stream.
public ValueTask SerializeAsync<T, TProvider>(Stream stream, in T? value, CancellationToken cancellationToken = default) where TProvider : IShapeable<T>
Parameters
stream
StreamThe stream to write to.
value
T- The value to serialize.
cancellationToken
CancellationToken- A cancellation token.
Returns
- ValueTask
A task that tracks the async serialization.
Type Parameters
T
The type to be serialized. TProvider
SerializeObject(ref MessagePackWriter, object?, ITypeShape, CancellationToken)
Serializes an untyped value.
public void SerializeObject(ref MessagePackWriter writer, object? value, ITypeShape shape, CancellationToken cancellationToken = default)
Parameters
writer
MessagePackWriterThe msgpack writer to use.
value
objectThe value to serialize.
shape
ITypeShapeThe shape of the value to serialize.
cancellationToken
CancellationTokenA cancellation token.
Examples
The following snippet demonstrates a way to use this method.
// Possible implementations of ITypeShapeProvider instances.
static readonly ITypeShapeProvider ReflectionBased = ReflectionTypeShapeProvider.Default;
static readonly ITypeShapeProvider SourceGenerated = Witness.ShapeProvider;
object TypelessSerializeRoundtrip(object value, ITypeShapeProvider provider)
{
// Acquire the type's shape. For this sample, we'll use the runtime type of the object.
ITypeShape shape = provider.GetShape(value.GetType()) ?? throw new ArgumentException("No shape available for runtime type", nameof(provider));
MessagePackSerializer serializer = new();
Sequence<byte> sequence = new();
// Serialize the object.
MessagePackWriter writer = new(sequence);
serializer.SerializeObject(ref writer, value, shape);
writer.Flush();
// Deserialize the object.
MessagePackReader reader = new(sequence);
return serializer.DeserializeObject(ref reader, shape)!;
}
[GenerateShape<Fruit>]
partial class Witness;
[GenerateShape]
internal partial record Fruit(int Seeds);
Serialize<T>(IBufferWriter<byte>, in T?, CancellationToken)
Serializes a value.
public void Serialize<T>(IBufferWriter<byte> writer, in T? value, CancellationToken cancellationToken = default) where T : IShapeable<T>
Parameters
writer
IBufferWriter<byte>The msgpack writer to use.
value
TThe value to serialize.
cancellationToken
CancellationTokenA cancellation token.
Type Parameters
T
The type to be serialized.
Serialize<T>(Stream, in T?, CancellationToken)
Serializes a value.
public void Serialize<T>(Stream stream, in T? value, CancellationToken cancellationToken = default) where T : IShapeable<T>
Parameters
stream
StreamThe stream to write to.
value
TThe value to serialize.
cancellationToken
CancellationTokenA cancellation token.
Type Parameters
T
The type to be serialized.
Serialize<T>(in T?, CancellationToken)
Serializes a value.
public byte[] Serialize<T>(in T? value, CancellationToken cancellationToken = default) where T : IShapeable<T>
Parameters
value
TThe value to serialize.
cancellationToken
CancellationTokenA cancellation token.
Returns
- byte[]
A byte array containing the serialized msgpack.
Type Parameters
T
The type to be serialized.
Serialize<T, TProvider>(IBufferWriter<byte>, in T?, CancellationToken)
Serializes a value.
public void Serialize<T, TProvider>(IBufferWriter<byte> writer, in T? value, CancellationToken cancellationToken = default) where TProvider : IShapeable<T>
Parameters
writer
IBufferWriter<byte>The msgpack writer to use.
value
TThe value to serialize.
cancellationToken
CancellationTokenA cancellation token.
Type Parameters
T
The type to be serialized.
TProvider
Serialize<T, TProvider>(Stream, in T?, CancellationToken)
Serializes a value.
public void Serialize<T, TProvider>(Stream stream, in T? value, CancellationToken cancellationToken = default) where TProvider : IShapeable<T>
Parameters
stream
StreamThe stream to write to.
value
TThe value to serialize.
cancellationToken
CancellationTokenA cancellation token.
Type Parameters
T
The type to be serialized.
TProvider
Serialize<T, TProvider>(in T?, CancellationToken)
Serializes a value.
public byte[] Serialize<T, TProvider>(in T? value, CancellationToken cancellationToken = default) where TProvider : IShapeable<T>
Parameters
value
TThe value to serialize.
cancellationToken
CancellationTokenA cancellation token.
Returns
- byte[]
A byte array containing the serialized msgpack.
Type Parameters
T
The type to be serialized.
TProvider