Decoding Guide
JDeck.MessagePack mirrors the JDeck decoding API over MessagePackValue instead of JsonElement.
Automatic Decoding
Automatic decoding needs a PolyType shape. Decoding.auto uses the reflection
shape provider, which suits desktop and server apps. AOT apps should pass a
shape with Decoding.autoWithShape instead.
let shape = ReflectionTypeShapeProvider.Default.GetTypeShape<MeterReading>()
let serializer = MessagePackSerializer()
let mutable reading = { Name = "temp"; Value = 21 }
let payload = serializer.Serialize(&reading, shape)
let autoResult = Decoding.auto<MeterReading>(payload)
printfn $"Auto: %A{autoResult}"
A decoder is defined as:
type Decoder<'TResult> = MessagePackValue -> Result<'TResult, DecodeError>
Use Required decoders when a value must exist and must match.
Use Optional decoders when a value can be Nil or a key can be missing.
Use VOptional decoders for the same cases with voption results.
Available Decoders
Both Required and Optional provide the same primitive set:
- Text and boolean:
string,boolean,char,guid,unit,binary - Numeric:
byte,sbyte,int16,uint16,int,uint32,int64,uint64,single,float,decimal -
Date and time:
dateTime,dateTimeOffset,timeSpan, in the native timestamp, extension, and array forms the automatic serializer uses
Records decode from maps by default, so navigation mirrors JSON properties:
Required.Map.get/Optional.Map.getread one named entryMap.seq,Map.list,Map.array,Map.map, andMap.dictread one named collection or mapRequired.Array.atreads one positional entry
Decoding MessagePack Maps
type Person = {
name: string
age: int
email: string option
}
let personDecoder: Decoder<Person> =
fun value -> decode {
let! name = Required.Map.get ("name", Required.string) value
and! age = Required.Map.get ("age", Required.int) value
and! email = Optional.Map.get ("email", Required.string) value
return { name = name; age = age; email = email }
}
let personValue =
Encode.entryMap [
"name", Encode.string "Ada"
"age", Encode.int 36
]
let personResult = personDecoder personValue
printfn $"Person: %A{personResult}"
Decoding Discriminated Unions
Use Decode.oneOf when one value can hold several shapes.
The positional form below reads a string tag at index 0.
type Shape =
| Circle of float
| Square of float
let shapeDecoder: Decoder<Shape> =
fun value -> decode {
let! tag = Decode.decodeAt Required.string 0 value
match tag with
| "circle" ->
let! radius = Decode.decodeAt Required.float 1 value
return Circle radius
| _ ->
let! side = Decode.decodeAt Required.float 1 value
return Square side
}
let shapeValue =
Encode.array [| Encode.string "circle"; Encode.float 1.5 |]
printfn $"Shape: %A{shapeDecoder shapeValue}"
Decoding a Full Document
One document is one top-level map.
Nested records are nested maps.
Collections are arrays inside the map.
A missing or Nil field decodes through Optional.Map.get.
Native fields use the forms from the encoding guide.
type Customer = { CustomerName: string; Email: string option }
type Line = { Sku: string; Qty: int; Price: decimal }
type Shipment = {
Id: System.Guid
Customer: Customer
Lines: Line array
Note: string option
Placed: System.DateTimeOffset
}
let customerDecoder: Decoder<Customer> =
fun value -> decode {
let! name = Required.Map.get ("CustomerName", Required.string) value
and! email = Optional.Map.get ("Email", Required.string) value
return { CustomerName = name; Email = email }
}
let lineDecoder: Decoder<Line> =
fun value -> decode {
let! sku = Required.Map.get ("Sku", Required.string) value
and! qty = Required.Map.get ("Qty", Required.int) value
and! price = Required.Map.get ("Price", Required.decimal) value
return { Sku = sku; Qty = qty; Price = price }
}
let shipmentDecoder: Decoder<Shipment> =
fun value -> decode {
let! id = Required.Map.get ("Id", Required.guid) value
and! customer = Required.Map.get ("Customer", customerDecoder) value
and! lines = Required.Map.array ("Lines", lineDecoder) value
and! note = Optional.Map.get ("Note", Required.string) value
and! placed = Required.Map.get ("Placed", Required.dateTimeOffset) value
return {
Id = id
Customer = customer
Lines = lines
Note = note
Placed = placed
}
}
let shipment: Shipment = {
Id = System.Guid("3f2504e0-4f89-11d3-9a0c-0305e82c3301")
Customer = { CustomerName = "Ada"; Email = Some "ada@x.io" }
Lines = [|
{ Sku = "KB-1"; Qty = 2; Price = 49.90m }
{ Sku = "MS-2"; Qty = 1; Price = 29.90m }
|]
Note = None
Placed = System.DateTimeOffset(2026, 6, 26, 3, 20, 11, System.TimeSpan.FromHours 2)
}
let shipmentBytes = Serializing.auto shipment
let shipmentResult = Decoding.fromBytes (shipmentBytes, shipmentDecoder)
printfn $"Shipment from auto bytes: %A{shipmentResult}"
The automatic writer produced those bytes.
The manual decoder reads them field by field.
The test suite proves the reverse direction too.
One manual encoder writes the same document.
Decoding.auto then reads it as the same record.
Entry Points
Decoding.fromValueruns a decoder on one decodedMessagePackValue.Decoding.fromBytesreads oneMessagePackValue, then runs a decoder.Decoding.fromMemoryandDecoding.fromSequencedo the same for buffers.Decoding.fromStreambuffers one stream, then runs a decoder.Decoding.fromBytesColcollects every error instead of the first one.- The
Colforms exist for values, memory, sequences, and streams too. Decoding.autoandDecoding.autoWithShapedelegate toMessagePackSerializer.Decoding.autoalso reads a stream.Decoding.autoFromMemoryreads one memory buffer with one serializer.
let streamResult =
use stream = new System.IO.MemoryStream(shipmentBytes)
Decoding.fromStream (stream, shipmentDecoder)
printfn $"Shipment from stream: %A{streamResult}"
val string: value: 'T -> string
--------------------
type string = System.String
val int: value: 'T -> int (requires member op_Explicit)
--------------------
type int = int32
--------------------
type int<'Measure> = int
type MessagePackValue = new: value: byte -> unit + 16 overloads member Equals: other: MessagePackValue -> bool + 1 overload member GetHashCode: unit -> int member StructuralEquals: other: MessagePackValue -> bool member ToString: unit -> string static member op_Explicit: token: MessagePackValue -> byte + 17 overloads static member op_Implicit: value: byte -> MessagePackValue + 17 overloads static val Nil: MessagePackValue member Kind: MessagePackValueKind member ValueAsArray: ReadOnlyMemory<MessagePackValue> ...
<summary> A variant type that can represent any of the MessagePack primitives. </summary>
--------------------
MessagePackValue ()
(+0 other overloads)
MessagePackValue(value: byte) : MessagePackValue
(+0 other overloads)
MessagePackValue(value: sbyte) : MessagePackValue
(+0 other overloads)
MessagePackValue(value: uint16) : MessagePackValue
(+0 other overloads)
MessagePackValue(value: int16) : MessagePackValue
(+0 other overloads)
MessagePackValue(value: uint32) : MessagePackValue
(+0 other overloads)
MessagePackValue(value: int) : MessagePackValue
(+0 other overloads)
MessagePackValue(value: uint64) : MessagePackValue
(+0 other overloads)
MessagePackValue(value: int64) : MessagePackValue
(+0 other overloads)
MessagePackValue(value: bool) : MessagePackValue
(+0 other overloads)
--------------------
MessagePackSerializer() : MessagePackSerializer
<summary> Provides a <see cref="T:PolyType.ITypeShapeProvider" /> implementation that uses reflection. </summary>
<summary> Gets the default provider instance using configuration supported by the current platform. </summary>
ReflectionTypeShapeProvider.GetTypeShape(``type`` : System.Type) : PolyType.ITypeShape
(+0 other overloads)
(extension) MessagePackSerializer.Serialize<'T,'TProvider>(value: inref<'T>, ?cancellationToken: System.Threading.CancellationToken) : byte array
(+0 other overloads)
MessagePackSerializer.Serialize<'T,'TProvider (requires 'TProvider :> PolyType.IShapeable<'T>)>(value: inref<'T>, ?cancellationToken: System.Threading.CancellationToken) : byte array
(+0 other overloads)
MessagePackSerializer.Serialize<'T (requires 'T :> PolyType.IShapeable<'T>)>(value: inref<'T>, ?cancellationToken: System.Threading.CancellationToken) : byte array
(+0 other overloads)
(extension) MessagePackSerializer.Serialize<'T>(writer: byref<MessagePackWriter>, value: inref<'T>, ?cancellationToken: System.Threading.CancellationToken) : unit
(+0 other overloads)
(extension) MessagePackSerializer.Serialize<'T>(writer: System.Buffers.IBufferWriter<byte>, value: inref<'T>, ?cancellationToken: System.Threading.CancellationToken) : unit
(+0 other overloads)
(extension) MessagePackSerializer.Serialize<'T>(stream: System.IO.Stream, value: inref<'T>, ?cancellationToken: System.Threading.CancellationToken) : unit
(+0 other overloads)
(extension) MessagePackSerializer.Serialize<'T,'TProvider>(writer: byref<MessagePackWriter>, value: inref<'T>, ?cancellationToken: System.Threading.CancellationToken) : unit
(+0 other overloads)
(extension) MessagePackSerializer.Serialize<'T,'TProvider>(writer: System.Buffers.IBufferWriter<byte>, value: inref<'T>, ?cancellationToken: System.Threading.CancellationToken) : unit
(+0 other overloads)
(extension) MessagePackSerializer.Serialize<'T,'TProvider>(stream: System.IO.Stream, value: inref<'T>, ?cancellationToken: System.Threading.CancellationToken) : unit
(+0 other overloads)
<summary> Decodes MessagePack payloads with JDeck decoders or automatic shapes. There is no fromString: MessagePack is a binary format. </summary>
static member Decoding.auto: bytes: byte array -> Result<'TResult,DecodeError>
static member Decoding.auto: serializer: MessagePackSerializer * stream: System.IO.Stream -> Result<'TResult,DecodeError>
static member Decoding.auto: serializer: MessagePackSerializer * bytes: byte array -> Result<'TResult,DecodeError>
module Result from Microsoft.FSharp.Core
--------------------
type Result<'T,'TError> = | Ok of ResultValue: 'T | Error of ErrorValue: 'TError
module DecodeError from JDeck.MessagePack
--------------------
type DecodeError = { value: MessagePackValue kind: MessagePackValueKind targetType: Type message: string exn: exn option index: int option property: string option }
<summary> Error details for a failed MessagePackValue decode. </summary>
<summary> Required decoders fail when the value is missing or has the wrong kind. </summary>
<summary> Reads entries of a Map value by string key. </summary>
static member Required.Map.get: key: string * decoder: Decoder<'TResult> -> Decoder<'TResult>
<summary> Optional decoders return None for Nil values. </summary>
<summary> Reads entries of a Map value by string key, None when absent or Nil. </summary>
static member Optional.Map.get: key: string * decoder: Decoder<'TResult> -> Decoder<'TResult option>
val float: value: 'T -> float (requires member op_Explicit)
--------------------
type float = System.Double
--------------------
type float<'Measure> = float
module Decode from JDeck.MessagePack.Decode
--------------------
module Decode from JDeck.MessagePack
val decimal: value: 'T -> decimal (requires member op_Explicit)
--------------------
type decimal = System.Decimal
--------------------
type decimal<'Measure> = decimal
type Guid = new: b: byte array -> unit + 6 overloads member CompareTo: value: Guid -> int + 1 overload member Equals: g: Guid -> bool + 1 overload member GetHashCode: unit -> int member ToByteArray: unit -> byte array + 1 overload member ToString: unit -> string + 2 overloads member TryFormat: utf8Destination: Span<byte> * bytesWritten: byref<int> * ?format: ReadOnlySpan<char> -> bool + 1 overload member TryWriteBytes: destination: Span<byte> -> bool + 1 overload static member (<) : left: Guid * right: Guid -> bool static member (<=) : left: Guid * right: Guid -> bool ...
<summary>Represents a globally unique identifier (GUID).</summary>
--------------------
System.Guid ()
System.Guid(b: byte array) : System.Guid
System.Guid(b: System.ReadOnlySpan<byte>) : System.Guid
System.Guid(g: string) : System.Guid
System.Guid(b: System.ReadOnlySpan<byte>, bigEndian: bool) : System.Guid
System.Guid(a: int, b: int16, c: int16, d: byte array) : System.Guid
System.Guid(a: int, b: int16, c: int16, d: byte, e: byte, f: byte, g: byte, h: byte, i: byte, j: byte, k: byte) : System.Guid
System.Guid(a: uint32, b: uint16, c: uint16, d: byte, e: byte, f: byte, g: byte, h: byte, i: byte, j: byte, k: byte) : System.Guid
type DateTimeOffset = new: date: DateOnly * time: TimeOnly * offset: TimeSpan -> unit + 8 overloads member Add: timeSpan: TimeSpan -> DateTimeOffset member AddDays: days: float -> DateTimeOffset member AddHours: hours: float -> DateTimeOffset member AddMicroseconds: microseconds: float -> DateTimeOffset member AddMilliseconds: milliseconds: float -> DateTimeOffset member AddMinutes: minutes: float -> DateTimeOffset member AddMonths: months: int -> DateTimeOffset member AddSeconds: seconds: float -> DateTimeOffset member AddTicks: ticks: int64 -> DateTimeOffset ...
<summary>Represents a point in time, typically expressed as a date and time of day, relative to Coordinated Universal Time (UTC).</summary>
--------------------
System.DateTimeOffset ()
System.DateTimeOffset(dateTime: System.DateTime) : System.DateTimeOffset
System.DateTimeOffset(dateTime: System.DateTime, offset: System.TimeSpan) : System.DateTimeOffset
System.DateTimeOffset(ticks: int64, offset: System.TimeSpan) : System.DateTimeOffset
System.DateTimeOffset(date: System.DateOnly, time: System.TimeOnly, offset: System.TimeSpan) : System.DateTimeOffset
System.DateTimeOffset(year: int, month: int, day: int, hour: int, minute: int, second: int, offset: System.TimeSpan) : System.DateTimeOffset
System.DateTimeOffset(year: int, month: int, day: int, hour: int, minute: int, second: int, millisecond: int, offset: System.TimeSpan) : System.DateTimeOffset
System.DateTimeOffset(year: int, month: int, day: int, hour: int, minute: int, second: int, millisecond: int, calendar: System.Globalization.Calendar, offset: System.TimeSpan) : System.DateTimeOffset
System.DateTimeOffset(year: int, month: int, day: int, hour: int, minute: int, second: int, millisecond: int, microsecond: int, offset: System.TimeSpan) : System.DateTimeOffset
System.DateTimeOffset(year: int, month: int, day: int, hour: int, minute: int, second: int, millisecond: int, microsecond: int, calendar: System.Globalization.Calendar, offset: System.TimeSpan) : System.DateTimeOffset
static member Required.Map.array: key: string * decoder: Decoder<'TResult> -> Decoder<'TResult array>
type TimeSpan = new: hours: int * minutes: int * seconds: int -> unit + 4 overloads member Add: ts: TimeSpan -> TimeSpan member CompareTo: value: obj -> int + 1 overload member Divide: divisor: float -> TimeSpan + 1 overload member Duration: unit -> TimeSpan member Equals: value: obj -> bool + 2 overloads member GetHashCode: unit -> int member Multiply: factor: float -> TimeSpan member Negate: unit -> TimeSpan member Subtract: ts: TimeSpan -> TimeSpan ...
<summary>Represents a time interval.</summary>
--------------------
System.TimeSpan ()
System.TimeSpan(ticks: int64) : System.TimeSpan
System.TimeSpan(hours: int, minutes: int, seconds: int) : System.TimeSpan
System.TimeSpan(days: int, hours: int, minutes: int, seconds: int) : System.TimeSpan
System.TimeSpan(days: int, hours: int, minutes: int, seconds: int, milliseconds: int) : System.TimeSpan
System.TimeSpan(days: int, hours: int, minutes: int, seconds: int, milliseconds: int, microseconds: int) : System.TimeSpan
System.TimeSpan.FromHours(value: float) : System.TimeSpan
System.TimeSpan.FromHours(hours: int, ?minutes: int64, ?seconds: int64, ?milliseconds: int64, ?microseconds: int64) : System.TimeSpan
<summary> Serializes F# values and manual encoder output to MessagePack bytes. Automatic members use a PolyType shape. Manual members run one encoder to a MessagePackValue, then write that value with the serializer. </summary>
static member Serializing.auto: serializer: MessagePackSerializer * value: 'T -> byte array
type MemoryStream = inherit Stream new: unit -> unit + 6 overloads member BeginRead: buffer: byte array * offset: int * count: int * callback: AsyncCallback * state: obj -> IAsyncResult member BeginWrite: buffer: byte array * offset: int * count: int * callback: AsyncCallback * state: obj -> IAsyncResult member CopyTo: destination: Stream * bufferSize: int -> unit member CopyToAsync: destination: Stream * bufferSize: int * cancellationToken: CancellationToken -> Task member EndRead: asyncResult: IAsyncResult -> int member EndWrite: asyncResult: IAsyncResult -> unit member Flush: unit -> unit member FlushAsync: cancellationToken: CancellationToken -> Task ...
<summary>Creates a stream whose backing store is memory.</summary>
--------------------
System.IO.MemoryStream() : System.IO.MemoryStream
System.IO.MemoryStream(buffer: byte array) : System.IO.MemoryStream
System.IO.MemoryStream(capacity: int) : System.IO.MemoryStream
System.IO.MemoryStream(buffer: byte array, writable: bool) : System.IO.MemoryStream
System.IO.MemoryStream(buffer: byte array, index: int, count: int) : System.IO.MemoryStream
System.IO.MemoryStream(buffer: byte array, index: int, count: int, writable: bool) : System.IO.MemoryStream
System.IO.MemoryStream(buffer: byte array, index: int, count: int, writable: bool, publiclyVisible: bool) : System.IO.MemoryStream
JDeck