CBOR in .NET with System.Formats.Cbor: an introduction
Andrew Lock introduces CBOR, a binary serialization format positioned as a more compact alternative to JSON, and shows how to use the System.Formats.Cbor package. The post walks through writing and reading CBOR with CborWriter and CborReader and explains the conformance modes that control the output.
Key points
- The System.Formats.Cbor NuGet package adds official CBOR support in .NET 10 and also targets .NET Framework and .NET Standard 2.0.
- When you know the element count, pass it to WriteStartMap or WriteStartArray; otherwise an indefinite-length item is written.
- CborWriter buffers the document until Encode or TryEncode is called and throws if the document is malformed.
- CborConformanceMode.Canonical sorts map keys and uses the smallest integer encodings, giving a deterministic output.
- CborReader is low level: there is no automatic mapping to classes, so you write the decoding logic yourself.
CBOR, short for Concise Binary Object Representation, is an IETF standard for binary serialization. It supports the same data types as JSON, adds native binary values, and aims for smaller payloads and simpler decoders. It is popular in IoT scenarios and also supports streaming with indefinite-length items.
With .NET 10, official CBOR encoding and decoding arrived through the System.Formats.Cbor NuGet package, which also targets .NET Framework and .NET Standard 2.0. The API is low level: CborWriter builds the document and CborReader parses it, and you work with primitive values rather than automatic object mapping. The writer offers conformance modes, such as Canonical, which sorts map keys and produces a stable encoding. The author compares CBOR with Protobuf and MessagePack and includes full code samples in the original post.
Real-world use
- Receiving sensor readings from IoT devices in a compact binary format and parsing them in a .NET service.
- Designing a network protocol or queue message where JSON payloads are too large or too slow to decode.
- Producing deterministic CBOR for signing or comparison scenarios using the Canonical conformance mode.
Why it matters
If JSON size or parsing cost matters, .NET 10 now offers a first-party CBOR option without third-party dependencies. The API is low level, so you need to plan mapping and error handling yourself.