High-performance CBOR (RFC 8949) serialization framework for .Net (C#)
High-performance CBOR serialization framework for .Net (C#)
https://www.nuget.org/packages/Dahomey.Cbor/
Install-Package Dahomey.Cbor
dotnet restore
dotnet pack -c Release
Any C# class be deserialized from a CBOR buffer Stream:
class CustomObject
{
...
}
CustomObject customObject = await Cbor.DeserializeAsync<CustomObject>(stream);
Another option consists in using Dahomey.Cbor object model to deserialize the buffer in a more generic CborObject
object:
CborObject cborObject = await Cbor.DeserializeAsync<CborObject>(stream);
Any C# class can be serialized to CBOR buffer Stream:
CustomObject customObject = new CustomObject
{
...
};
await Cbor.SerializeAsync(customObject, stream);
As for deserialization a more generic solution consists in using CborObject
object:
CborObject obj = new CborObject
{
["string"] = "foo",
["number"] = 12.12,
["bool"] = true,
["null"] = null,
["array"] = new CborArray {1, 2},
["object"] = new CborObject { [ "id" ] = 1 },
};
await Cbor.SerializeAsync(cborObject, stream);
If you need to write a customer converter for a specific class, you can inherit a custom converter class for CborConverterBase<T>. An example can be found here: https://github.com/dahomey-technologies/Dahomey.Cbor/blob/master/src/Dahomey.Cbor.Tests/GuidConverter.cs
Then you can register you custom converter in 3 ways.
[CborConverter(typeof(CustomObjectConverter))]
class CustomObject
{
}
CborOptions.Default.Registry.ConverterRegistry.RegisterConverter(typeof(CustomObject), new CustomObjectConverter());
class CustomObject2
{
[CborConverter(typeof(CustomObjectConverter))]
public CustomObject CustomObject { get; set; }
}
The last two options are useful when you write a custom cbor converter for a class you can't decorate with the CborConverterAttribute because you don't own it like the above example with System.Guid.
CborConverters are use in the heart of the library for standard types and auto discovered custom classes by reflection. It means you will benefit of the same features and performance.