Introduction
JSON has become the standard format for exchanging data between web applications, mobile clients, and backend services. It is easy to read, supported by almost every programming language, and works well with HTTP APIs. However, JSON is not always the most efficient choice when applications exchange large amounts of structured data.
Consider a mobile application that sends thousands of telemetry records to an ASP.NET Core API. Each record may contain timestamps, identifiers, numeric values, and status information. JSON represents these values using text, property names, quotation marks, commas, and other structural characters. When the same property names appear repeatedly across thousands of records, the payload contains a significant amount of repeated information.
Concise Binary Object Representation (CBOR) provides another way to represent structured data. It uses a compact binary encoding instead of a text-based representation. This can reduce payload sizes, particularly when applications exchange repetitive data or communicate with resource-constrained devices.
.NET provides the System.Formats.Cbor library for reading and writing CBOR data. It includes CborWriter and CborReader, which allow developers to encode and decode values without implementing the binary format themselves.
In this article, we will explore CBOR, compare it with JSON, build a C# example that encodes and decodes API data, and understand how to integrate CBOR into an ASP.NET Core application.
What Is CBOR?
CBOR is a binary data format designed to represent structured information in a compact way. It supports common data types such as integers, floating-point numbers, strings, byte arrays, arrays, maps, Boolean values, and null values.
Unlike JSON, CBOR does not need to represent every value as readable text. For example, an integer can be encoded directly as a binary value instead of being represented by a sequence of decimal characters.
CBOR also supports maps, which are similar to JSON objects, and arrays, which are similar to JSON arrays.
Consider the following JSON document:
{
"deviceId": "DEV-1001",
"temperature": 28.5,
"active": true,
"timestamp": 1795594200
}The same information can be represented using CBOR as a binary map. The property names and values are encoded according to CBOR's data model rather than being stored as JSON text.
This makes CBOR particularly useful when the same structure is transmitted frequently.
Some common scenarios include:
IoT devices sending telemetry to backend services.
Mobile applications exchanging compact API messages.
Distributed systems transferring structured events.
Applications communicating with constrained hardware.
Systems where network bandwidth is limited.
APIs that process large volumes of repetitive records.
CBOR is standardized through RFC 8949 and supports different encoding options, including definite-length and indefinite-length data structures.
Understanding System.Formats.Cbor in .NET
The System.Formats.Cbor package provides the APIs required to work with CBOR data in C#.
The main types are:
Type | Purpose |
|---|---|
CborWriter | Encodes values into CBOR format |
CborReader | Reads and decodes CBOR values |
CborConformanceMode | Controls the accepted CBOR encoding rules |
CborContentException | Represents invalid CBOR content |
CborReaderState | Describes the reader's current state |
CborTag | Represents CBOR semantic tags |
CborWriter is responsible for creating the binary representation. Developers call methods such as WriteTextString, WriteInt32, WriteBoolean, and WriteStartMap to construct the data.
CborReader performs the reverse operation. It reads the encoded bytes and provides methods such as ReadTextString, ReadInt32, ReadBoolean, and ReadStartMap.
The library does not automatically convert arbitrary C# objects into CBOR. Developers define how application data maps to CBOR values, which gives them control over the encoded structure.
Installing the CBOR Package
For a traditional .NET application, install the package using:
dotnet add package System.Formats.CborFor a file-based C# application, add the package directive at the beginning of the source file:
#:package [email protected]The package provides support for reading and writing CBOR data and includes the reader and writer APIs.
If you are using a different target framework, select a compatible package version. You should also use a version supported by your application's deployment environment.
Creating a C# Model for API Data
Before encoding data, define the structure that the application needs to exchange.
For this example, we will use a telemetry record containing a device identifier, temperature, active status, and timestamp.
public sealed record DeviceTelemetry(
string DeviceId,
double Temperature,
bool IsActive,
long Timestamp);This record represents a typical API message sent by an IoT device.
The same structure could be represented using JSON, but we will encode it directly into CBOR using CborWriter.
Encoding Data Using CborWriter
The first step is to create a CborWriter and write the application data into a CBOR map.
using System.Formats.Cbor;
static byte[] EncodeTelemetry(DeviceTelemetry telemetry)
{
var writer = new CborWriter(
CborConformanceMode.Strict);
writer.WriteStartMap(4);
writer.WriteTextString("deviceId");
writer.WriteTextString(telemetry.DeviceId);
writer.WriteTextString("temperature");
writer.WriteDouble(telemetry.Temperature);
writer.WriteTextString("active");
writer.WriteBoolean(telemetry.IsActive);
writer.WriteTextString("timestamp");
writer.WriteInt64(telemetry.Timestamp);
writer.WriteEndMap();
return writer.Encode();
}The implementation starts by creating a CborWriter using strict conformance mode. This mode validates that the generated data follows the selected CBOR conformance requirements.
WriteStartMap(4) indicates that the map contains four key-value pairs.
Each property name is written as a text string, followed by its corresponding value. The writer uses the appropriate CBOR representation for each value type.
For example, the temperature is written as a floating-point number, while the active property is written as a Boolean value.
WriteEndMap completes the map, and Encode returns the resulting byte array.
The important difference is that the application is writing structured binary data directly. It does not first create a JSON string and then convert that string into bytes.
Decoding CBOR Data Using CborReader
Encoding is only one part of the process. An API also needs to read the binary payload and convert it back into application data.
CborReader provides a forward-only reading model. It processes the encoded data in sequence and exposes methods for reading the expected value types.
The following example decodes the telemetry map:
using System.Formats.Cbor;
static DeviceTelemetry DecodeTelemetry(byte[] data)
{
var reader = new CborReader(
data,
CborConformanceMode.Strict);
int? mapLength = reader.ReadStartMap();
if (mapLength != 4)
{
throw new InvalidDataException(
"Unexpected telemetry map structure.");
}
string deviceId = string.Empty;
double temperature = 0;
bool isActive = false;
long timestamp = 0;
for (int i = 0; i < mapLength.Value; i++)
{
string key = reader.ReadTextString();
switch (key)
{
case "deviceId":
deviceId = reader.ReadTextString();
break;
case "temperature":
temperature = reader.ReadDouble();
break;
case "active":
isActive = reader.ReadBoolean();
break;
case "timestamp":
timestamp = reader.ReadInt64();
break;
default:
throw new InvalidDataException(
$"Unknown property: {key}");
}
}
reader.ReadEndMap();
if (reader.BytesRemaining != 0)
{
throw new InvalidDataException(
"Unexpected trailing CBOR data.");
}
return new DeviceTelemetry(
deviceId,
temperature,
isActive,
timestamp);
}The reader first opens the map and checks its expected length. It then reads each key and determines which value should be processed.
This example assumes a fixed schema. If a new property is introduced, the decoding logic must be updated or designed to handle additional fields.
The BytesRemaining check ensures that the application does not silently accept additional encoded data after the expected map.
In production systems, validate required fields, numeric ranges, and string lengths before using the decoded values.
Comparing JSON and CBOR Payload Sizes
One of the main reasons to consider CBOR is its compact representation.
Let's compare the same telemetry object in JSON and CBOR.
using System.Formats.Cbor;
using System.Text.Json;
var telemetry = new DeviceTelemetry(
"DEV-1001",
28.5,
true,
1795594200);
byte[] jsonBytes =
JsonSerializer.SerializeToUtf8Bytes(telemetry);
byte[] cborBytes =
EncodeTelemetry(telemetry);
Console.WriteLine(
$"JSON size: {jsonBytes.Length} bytes");
Console.WriteLine(
$"CBOR size: {cborBytes.Length} bytes");
double reduction =
(1.0 - (double)cborBytes.Length / jsonBytes.Length) * 100;
Console.WriteLine(
$"Size reduction: {reduction:F2}%");The program serializes the same object into two different formats and compares their byte lengths.
The result depends on the property names, values, numeric representations, and CBOR encoding choices. It should not be treated as a universal compression percentage.
CBOR is not guaranteed to produce a smaller payload for every document. Small JSON objects containing short values may have similar sizes, while repetitive structures and binary-oriented data can benefit more.
For an actual application, measure representative requests rather than relying on a single example.
Integrating CBOR With ASP.NET Core APIs
After implementing encoding and decoding, the next step is using CBOR in an HTTP API.
ASP.NET Core can receive binary request content through HttpRequest.Body. The application can read those bytes and pass them to CborReader.
For example, the following minimal API endpoint accepts a CBOR telemetry payload:
using System.Formats.Cbor;
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapPost("/telemetry", async (HttpRequest request) =>
{
if (!string.Equals(
request.ContentType,
"application/cbor",
StringComparison.OrdinalIgnoreCase))
{
return Results.StatusCode(
StatusCodes.Status415UnsupportedMediaType);
}
try
{
using var memory = new MemoryStream();
await request.Body.CopyToAsync(memory);
if (memory.Length > 64 * 1024)
{
return Results.StatusCode(
StatusCodes.Status413PayloadTooLarge);
}
byte[] payload = memory.ToArray();
DeviceTelemetry telemetry =
DecodeTelemetry(payload);
if (string.IsNullOrWhiteSpace(telemetry.DeviceId))
{
return Results.BadRequest(
"Device identifier is required.");
}
if (telemetry.Temperature is < -50 or > 150)
{
return Results.BadRequest(
"Temperature value is outside the accepted range.");
}
return Results.Ok(new
{
Message = "Telemetry received",
telemetry.DeviceId
});
}
catch (CborContentException)
{
return Results.BadRequest(
"Invalid CBOR payload.");
}
catch (InvalidDataException)
{
return Results.BadRequest(
"Unexpected telemetry structure.");
}
});
app.Run();The endpoint checks the Content-Type header before processing the request. It expects application/cbor, which identifies the incoming body as CBOR data.
The example also limits the request size to 64 KB. This is important because an API should not accept unlimited binary input from clients.
After reading the request, the endpoint decodes the payload and validates the telemetry values before accepting the data.
For larger payloads, avoid copying the entire request body into a MemoryStream and then creating another byte array. Configure request size limits and use an appropriate streaming or bounded-buffer approach for the expected workload.
A successful response can use JSON while the incoming request uses CBOR. Request and response formats do not have to be identical, although supporting both directions may be useful for clients that benefit from compact responses as well.
Sending CBOR From an HttpClient Application
A .NET client can send the encoded payload using HttpClient.
using System.Net.Http.Headers;
var telemetry = new DeviceTelemetry(
"DEV-1001",
28.5,
true,
DateTimeOffset.UtcNow.ToUnixTimeSeconds());
byte[] payload = EncodeTelemetry(telemetry);
using var httpClient = new HttpClient();
using var content = new ByteArrayContent(payload);
content.Headers.ContentType =
new MediaTypeHeaderValue("application/cbor");
using var response = await httpClient.PostAsync(
"https://localhost:7001/telemetry",
content);
response.EnsureSuccessStatusCode();
Console.WriteLine("Telemetry sent successfully.");The client encodes the telemetry object and places the resulting bytes into ByteArrayContent.
The Content-Type header tells the server how to interpret the request body.
This approach works when both sides understand the same CBOR schema. An API that accepts only JSON will not automatically understand CBOR just because the request contains binary data.
Choosing the Right CBOR Conformance Mode
CborWriter and CborReader support different conformance modes.
The mode determines which CBOR encodings are accepted or generated.
Mode | Purpose |
|---|---|
Lax | Allows a broader range of CBOR encodings |
Strict | Enforces stricter encoding requirements |
Ctap2Canonical | Applies canonical encoding rules used by CTAP2 |
For a controlled API contract, strict mode is a reasonable starting point. It helps ensure that the producer and consumer follow consistent encoding rules.
Canonical encoding can be important when encoded data is used in cryptographic operations, digital signatures, or hashing. Two different CBOR encodings can represent equivalent logical values, so a consistent representation is necessary when byte-for-byte comparison matters.
Choose the mode according to the protocol requirements rather than assuming that one mode is suitable for every application.
Best Practices for Production Applications
Define a stable CBOR schema
The client and server must agree on the structure, property names, value types, and required fields. Document the schema and version it when changes could affect existing clients.
Validate binary input
Do not assume that a valid CBOR document contains valid business data. Check required properties, data types, numeric ranges, and maximum string lengths.
Set request size limits
Binary payloads can still be large. Configure limits at the API, reverse proxy, and hosting layers to prevent excessive memory consumption.
Measure real payload sizes
Compare JSON and CBOR using actual production-like data. Include serialization time, deserialization time, network transfer, and server processing in the evaluation.
Handle schema evolution
When an API adds new fields, older clients may not understand them. Decide whether unknown fields should be skipped, ignored, or rejected. Use an explicit versioning strategy for incompatible changes.
Keep content types consistent
Use application/cbor for CBOR request bodies and application/json for JSON. This makes it clear how the receiving endpoint should process the data.
Consider debugging requirements
CBOR is binary and cannot be inspected as easily as JSON. Provide logging that records useful metadata without exposing sensitive payload contents.
Common Mistakes to Avoid
One common mistake is assuming that CBOR is automatically compressed. CBOR is a compact binary representation, but it is not a general-purpose compression algorithm. If additional compression is needed, evaluate an HTTP content encoding such as Brotli or gzip.
Another mistake is treating CBOR maps as if their values always appear in a fixed property order. Applications should identify map entries by their keys rather than depending on the order in which properties were written.
Developers may also forget to validate the decoded data. A payload can be structurally valid CBOR but still contain an invalid device identifier, an unexpected temperature, or missing business information.
Finally, do not change an existing JSON API to CBOR without considering its clients. Every consumer must support the selected binary format and follow the same schema.
Advantages and Disadvantages
Advantages
Provides a compact binary representation of structured data.
Supports common values such as strings, numbers, arrays, maps, and Boolean values.
Can reduce network payload sizes for suitable data structures.
Provides dedicated reader and writer APIs in .NET.
Works well for IoT, telemetry, and bandwidth-sensitive applications.
Supports canonical encoding requirements for applications that need consistent representations.
Disadvantages
Binary payloads are harder to inspect manually than JSON.
Both API clients and servers must understand the CBOR schema.
Schema changes require careful compatibility planning.
Smaller payloads are not guaranteed for every data structure.
Developers need to implement mapping between C# models and CBOR values.
Existing JSON-based integrations may require additional client changes.
Summary
System.Formats.Cbor provides .NET developers with a straightforward way to encode and decode structured data using CBOR. Its CborWriter and CborReader classes make it possible to build compact binary API messages without implementing the encoding format manually.
CBOR can be particularly useful for telemetry, IoT communication, mobile applications, and services that exchange large volumes of repetitive structured data. It can reduce the amount of information transmitted over the network, although the actual benefit depends on the payload structure and encoding choices.
The most important consideration is the API contract. The client and server must agree on the CBOR structure, data types, validation rules, and versioning strategy.
For existing APIs, CBOR does not need to replace JSON everywhere. It can be introduced for selected endpoints where smaller payloads provide a measurable benefit while JSON remains available for clients that need a human-readable format.

Join the conversation! Your thoughts help the community grow.