The Shuttle.Core.Serialization package provides a consistent interface for serializing and deserializing objects.
dotnet add package Shuttle.Core.SerializationThe core of the library is the ISerializer interface:
public interface ISerializer
{
string Name { get; }
Task<object> DeserializeAsync(Type type, Stream stream, CancellationToken cancellationToken = default);
Task<Stream> SerializeAsync(object instance, CancellationToken cancellationToken = default);
}The following implementation is provided:
JsonSerializer: usesSystem.Text.Jsonfor serialization.SerializerService: used to manage multipleISerializerinstances.
To register the JsonSerializer, use the AddJsonSerializer extension method on IServiceCollection:
services.AddJsonSerializer(options =>
{
options.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
});The options is of type JsonSerializerOptions.
The ISerializerService can be used to manage multiple serializers:
public interface ISerializerService
{
IEnumerable<ISerializer> Serializers { get; }
ISerializerService Add(ISerializer serializer);
bool Contains(string name);
ISerializer Get(string name);
}You can use the SerializerService implementation to store and retrieve serializers by their Name:
var serializerService = new SerializerService();
serializerService.Add(new JsonSerializer(Options.Create(new JsonSerializerOptions())));
if (serializerService.Contains("Json"))
{
var serializer = serializerService.Get("Json");
}Task<Stream> SerializeAsync(object instance, CancellationToken cancellationToken = default);Returns the object as a Stream.
Task<object> DeserializeAsync(Type type, Stream stream, CancellationToken cancellationToken = default);Deserializes the Stream into an object of the given Type.
Task<T> DeserializeAsync<T>(Stream stream, CancellationToken cancellationToken = default);Deserializes the Stream into an object of the given type T.