Logo JDeck

Codecs and Serialization

The Codec module registers manual encoders and decoders as one XmlConverter inside XmlSerializerOptions. Automatic serialization then uses the manual codec only for the registered type.

A Manual Union Codec

type Shape =
  | Circle of float
  | Square of float

  static member Encoder: Encoder<Shape> =
    function
    | Circle r -> Encode.element "Circle" [ Encode.float r ]
    | Square s -> Encode.element "Square" [ Encode.float s ]

  static member Decoder: Decoder<Shape> =
    Decode.oneOf [
      fun el -> decode {
        let! r = Required.Element.get ("Circle", Required.float) el
        return Circle r
      }
      fun el -> decode {
        let! s = Required.Element.get ("Square", Required.float) el
        return Square s
      }
    ]

let options =
  XmlSerializerOptions() |> Codec.useCodec(Shape.Encoder, Shape.Decoder)

let xml = XmlSerializer.Serialize(Circle 1.5, options)
printfn $"%s{xml}"

let shapeBack = XmlSerializer.Deserialize<Shape>(xml, options)
printfn $"%A{shapeBack}"

Use Codec.useEncoder or Codec.useDecoder when only one direction needs help. Use Codec.useCodecWithOptions when a codec must read the active options.

Manual and Automatic Together

Decoding.auto delegates a whole payload to XmlSerializer. Decoding.fromString runs one manual decoder on the root element. Both return Result<'T, DecodeError>, so call sites handle both the same way.

[<CLIMutable>]
type Person = { Name: string; Age: int }

let autoResult =
  Decoding.auto<Person>("<Person><Name>Ada</Name><Age>36</Age></Person>")

printfn $"Auto: %A{autoResult}"

Attributes Are a Manual Choice

The automatic serializer maps every property to a child element. A field becomes an attribute only when the manual codec says so: the encoder writes it with Encode.attribute, and the decoder reads it with Required.Attribute.get or Optional.Attribute.get.

let taggedCircle =
  Encode.element "Circle" [ Encode.float 1.5 ]
  |> Encode.attribute("unit", "m")

let taggedUnit =
  Decoding.fromString(taggedCircle.ToString(), Required.Attribute.get("unit", Required.string))

printfn $"Unit: %A{taggedUnit}"
namespace CloudNimble
namespace CloudNimble.Text
namespace CloudNimble.Text.Xml
namespace JDeck
namespace JDeck.Xml
Multiple items
val float: value: 'T -> float (requires member op_Explicit)

--------------------
type float = System.Double

--------------------
type float<'Measure> = float
type Encoder<'T> = 'T -> Nodes.XmlNode
type Shape = | Circle of float | Square of float static member Decoder: Decoder<Shape> static member Encoder: Encoder<Shape>
union case Shape.Circle: float -> Shape
val r: float
module Encode from JDeck.Xml.Encoding
<summary> Provides functions for encoding values to XML nodes. All primitives format invariantly. Text values carry no type marker: XML has no native boolean, date, or null literal, so decoders parse the same lexical forms back. </summary>
val element: name: string -> children: Nodes.XmlNode seq -> Nodes.XmlNode
<summary> Builds an element node with the given local name and child nodes. </summary>
val float: value: float -> Nodes.XmlNode
union case Shape.Square: float -> Shape
val s: float
type Decoder<'TResult> = XmlElement -> Result<'TResult,DecodeError>
Multiple items
module Decode from JDeck.Xml.Decode

--------------------
module Decode from JDeck.Xml
val oneOf: decoders: Decoder<'TResult> seq -> Decoder<'TResult>
<summary> Tries each decoder in order and returns the first success, otherwise the first error. </summary>
val el: XmlElement
val decode: DecodeBuilder
module Required from JDeck.Xml.Decode
<summary> Decoders that fail when the value is missing, nil, or has the wrong shape. </summary>
type Element = static member array: name: string * decoder: Decoder<'TResult> -> (XmlElement -> Result<'TResult array,DecodeError>) + 3 overloads static member dict: name: string * decoder: Decoder<'TValue> -> (XmlElement -> Result<Dictionary<string,'TValue>,DecodeError>) + 3 overloads static member get: name: string * decoder: Decoder<'TResult> -> (XmlElement -> Result<'TResult,DecodeError>) + 3 overloads static member list: name: string * decoder: Decoder<'TResult> -> (XmlElement -> Result<'TResult list,DecodeError>) + 3 overloads static member map: name: string * decoder: Decoder<'TValue> -> (XmlElement -> Result<Map<string,'TValue>,DecodeError>) + 3 overloads static member seq: name: string * decoder: Decoder<'TResult> -> (XmlElement -> Result<'TResult seq,DecodeError>) + 3 overloads
<summary> Decodes a required child element by local name. Attributes hold scalars only; there are no sequence attributes. </summary>
static member Required.Element.get: name: string * decoder: CollectErrorsDecoder<'TResult> -> (XmlElement -> Result<'TResult,DecodeError list>)
static member Required.Element.get: name: string * decoder: Decoder<'TResult> -> (XmlElement -> Result<'TResult,DecodeError>)
static member Required.Element.get: namespaceUri: string * name: string * decoder: CollectErrorsDecoder<'TResult> -> (XmlElement -> Result<'TResult,DecodeError list>)
static member Required.Element.get: namespaceUri: string * name: string * decoder: Decoder<'TResult> -> (XmlElement -> Result<'TResult,DecodeError>)
val float: Decoder<float>
val options: XmlSerializerOptions
Multiple items
type XmlSerializerOptions = new: unit -> unit + 2 overloads member GetConverter: typeToConvert: Type -> XmlConverter member GetTypeInfo: ``type`` : Type -> XmlTypeInfo + 1 overload member MakeReadOnly: unit -> unit + 1 overload member TryGetTypeInfo: ``type`` : Type * typeInfo: byref<XmlTypeInfo> -> bool + 1 overload member AllowDuplicateProperties: bool member AttributeNamingPolicy: XmlNamingPolicy member AttributeStyle: XmlAttributeStyle member AttributesPerLine: int member CharHandling: XmlCharHandling ...
<summary> Provides options to be used with <see cref="T:CloudNimble.Text.Xml.XmlSerializer" />. This class cannot be inherited. </summary>
<remarks> This class is the XML counterpart of <c>System.Text.Json.JsonSerializerOptions</c>. An instance becomes read-only the first time it is used to serialize or deserialize, or when <see cref="M:CloudNimble.Text.Xml.XmlSerializerOptions.MakeReadOnly" /> is called. Create one instance and reuse it: the converters and type info it resolves are cached on the instance. </remarks>


--------------------
XmlSerializerOptions() : XmlSerializerOptions
XmlSerializerOptions(defaults: XmlSerializerDefaults) : XmlSerializerOptions
XmlSerializerOptions(options: XmlSerializerOptions) : XmlSerializerOptions
module Codec from JDeck.Xml
val useCodec: encoder: Encoder<'T> * decoder: Decoder<'T> -> options: XmlSerializerOptions -> XmlSerializerOptions
property Shape.Encoder: Encoder<Shape> with get
property Shape.Decoder: Decoder<Shape> with get
val xml: string
type XmlSerializer = static member Deserialize<'TValue> : xml: string * ?options: XmlSerializerOptions -> 'TValue + 44 overloads static member DeserializeAsync<'TValue> : xml: Stream * ?options: XmlSerializerOptions * ?cancellationToken: CancellationToken -> ValueTask<'TValue> + 6 overloads static member DeserializeAsyncEnumerable<'TValue> : xml: Stream * ?options: XmlSerializerOptions * ?cancellationToken: CancellationToken -> IAsyncEnumerable<'TValue> + 5 overloads static member Serialize<'TValue> : value: 'TValue * ?options: XmlSerializerOptions -> string + 19 overloads static member SerializeAsync<'TValue> : utf8Xml: Stream * value: 'TValue * ?options: XmlSerializerOptions * ?cancellationToken: CancellationToken -> Task + 5 overloads static member SerializeAsyncEnumerable<'TValue> : utf8Xml: Stream * values: IAsyncEnumerable<'TValue> * ?options: XmlSerializerOptions * ?cancellationToken: CancellationToken -> Task + 3 overloads static member SerializeToDocument<'TValue> : value: 'TValue * ?options: XmlSerializerOptions -> XmlDocument + 4 overloads static member SerializeToElement<'TValue> : value: 'TValue * ?options: XmlSerializerOptions -> XmlElement + 4 overloads static member SerializeToNode<'TValue> : value: 'TValue * ?options: XmlSerializerOptions -> XmlNode + 4 overloads static member SerializeToUtf8Bytes<'TValue> : value: 'TValue * ?options: XmlSerializerOptions -> byte array + 4 overloads ...
<summary> Provides functionality to serialize objects or value types to XML and to deserialize XML into objects or value types. This class cannot be inherited. </summary>
<remarks> This class is the XML counterpart of <c>System.Text.Json.JsonSerializer</c>. Every overload resolves an <see cref="T:CloudNimble.Text.Xml.Serialization.XmlTypeInfo" /> and then goes through one of the internal <c>Read</c> or <c>Write</c> methods in this file. All reading is done by <see cref="T:CloudNimble.Text.Xml.Utf8XmlReader" /> and all writing by <see cref="T:CloudNimble.Text.Xml.Utf8XmlWriter" />. </remarks>
XmlSerializer.Serialize<'TValue>(value: 'TValue, context: Serialization.XmlSerializerContext) : string
   (+0 other overloads)
XmlSerializer.Serialize<'TValue>(value: 'TValue, xmlTypeInfo: Serialization.XmlTypeInfo<'TValue>) : string
   (+0 other overloads)
XmlSerializer.Serialize<'TValue>(value: 'TValue, ?options: XmlSerializerOptions) : string
   (+0 other overloads)
XmlSerializer.Serialize<'TValue>(bufferWriter: System.Buffers.IBufferWriter<byte>, value: 'TValue, context: Serialization.XmlSerializerContext) : unit
   (+0 other overloads)
XmlSerializer.Serialize<'TValue>(bufferWriter: System.Buffers.IBufferWriter<byte>, value: 'TValue, xmlTypeInfo: Serialization.XmlTypeInfo<'TValue>) : unit
   (+0 other overloads)
XmlSerializer.Serialize<'TValue>(bufferWriter: System.Buffers.IBufferWriter<byte>, value: 'TValue, ?options: XmlSerializerOptions) : unit
   (+0 other overloads)
XmlSerializer.Serialize<'TValue>(utf8Xml: System.IO.Stream, value: 'TValue, context: Serialization.XmlSerializerContext) : unit
   (+0 other overloads)
XmlSerializer.Serialize<'TValue>(utf8Xml: System.IO.Stream, value: 'TValue, xmlTypeInfo: Serialization.XmlTypeInfo<'TValue>) : unit
   (+0 other overloads)
XmlSerializer.Serialize<'TValue>(utf8Xml: System.IO.Stream, value: 'TValue, ?options: XmlSerializerOptions) : unit
   (+0 other overloads)
XmlSerializer.Serialize<'TValue>(writer: Utf8XmlWriter, value: 'TValue, context: Serialization.XmlSerializerContext) : unit
   (+0 other overloads)
val printfn: format: Printf.TextWriterFormat<'T> -> 'T
val shapeBack: Shape
XmlSerializer.Deserialize<'TValue>(node: Nodes.XmlNode, context: Serialization.XmlSerializerContext) : 'TValue
   (+0 other overloads)
XmlSerializer.Deserialize<'TValue>(node: Nodes.XmlNode, xmlTypeInfo: Serialization.XmlTypeInfo<'TValue>) : 'TValue
   (+0 other overloads)
XmlSerializer.Deserialize<'TValue>(node: Nodes.XmlNode, ?options: XmlSerializerOptions) : 'TValue
   (+0 other overloads)
XmlSerializer.Deserialize<'TValue>(element: XmlElement, context: Serialization.XmlSerializerContext) : 'TValue
   (+0 other overloads)
XmlSerializer.Deserialize<'TValue>(element: XmlElement, xmlTypeInfo: Serialization.XmlTypeInfo<'TValue>) : 'TValue
   (+0 other overloads)
XmlSerializer.Deserialize<'TValue>(element: XmlElement, ?options: XmlSerializerOptions) : 'TValue
   (+0 other overloads)
XmlSerializer.Deserialize<'TValue>(document: XmlDocument, context: Serialization.XmlSerializerContext) : 'TValue
   (+0 other overloads)
XmlSerializer.Deserialize<'TValue>(document: XmlDocument, xmlTypeInfo: Serialization.XmlTypeInfo<'TValue>) : 'TValue
   (+0 other overloads)
XmlSerializer.Deserialize<'TValue>(document: XmlDocument, ?options: XmlSerializerOptions) : 'TValue
   (+0 other overloads)
XmlSerializer.Deserialize<'TValue>(xml: System.IO.Stream, context: Serialization.XmlSerializerContext) : 'TValue
   (+0 other overloads)
Multiple items
type CLIMutableAttribute = inherit Attribute new: unit -> CLIMutableAttribute

--------------------
new: unit -> CLIMutableAttribute
type Person = { Name: string Age: int }
Multiple items
val string: value: 'T -> string

--------------------
type string = System.String
Multiple items
val int: value: 'T -> int (requires member op_Explicit)

--------------------
type int = int32

--------------------
type int<'Measure> = int
val autoResult: Result<Person,DecodeError>
type Decoding = static member auto: value: string -> Result<'TResult,DecodeError> + 2 overloads static member autoWithOptions: value: string * options: XmlSerializerOptions -> Result<'TResult,DecodeError> + 2 overloads static member fromBytes: value: byte array * decoder: Decoder<'TResult> -> Result<'TResult,DecodeError> static member fromBytesCol: value: byte array * decoder: CollectErrorsDecoder<'TResult> -> Result<'TResult,DecodeError list> static member fromElement: element: XmlElement * decoder: Decoder<'TResult> -> Result<'TResult,DecodeError> static member fromStream: value: Stream * decoder: Decoder<'TResult> -> Task<Result<'TResult,DecodeError>> static member fromStreamCol: value: Stream * decoder: CollectErrorsDecoder<'TResult> -> Task<Result<'TResult,DecodeError list>> static member fromString: value: string * decoder: Decoder<'TResult> -> Result<'TResult,DecodeError> static member fromStringCol: value: string * decoder: CollectErrorsDecoder<'TResult> -> Result<'TResult,DecodeError list>
<summary> Entry points that parse XML text and run a decoder on the document element. </summary>
static member Decoding.auto: value: System.IO.Stream -> System.Threading.Tasks.Task<Result<'TResult,DecodeError>>
static member Decoding.auto: value: byte array -> Result<'TResult,DecodeError>
static member Decoding.auto: value: string -> Result<'TResult,DecodeError>
val taggedCircle: Nodes.XmlNode
val attribute: name: string * value: string -> node: Nodes.XmlNode -> Nodes.XmlNode
<summary> Sets an attribute on an element node and returns the node. </summary>
val taggedUnit: Result<string,DecodeError>
static member Decoding.fromString: value: string * decoder: Decoder<'TResult> -> Result<'TResult,DecodeError>
Nodes.XmlNode.ToString() : string
type Attribute = static member get: namespaceUri: string * name: string * decoder: Decoder<'TResult> -> (XmlElement -> Result<'TResult,DecodeError>) + 3 overloads
static member Required.Attribute.get: name: string * decoder: CollectErrorsDecoder<'TResult> -> (XmlElement -> Result<'TResult,DecodeError list>)
static member Required.Attribute.get: name: string * decoder: Decoder<'TResult> -> (XmlElement -> Result<'TResult,DecodeError>)
static member Required.Attribute.get: namespaceUri: string * name: string * decoder: CollectErrorsDecoder<'TResult> -> (XmlElement -> Result<'TResult,DecodeError list>)
static member Required.Attribute.get: namespaceUri: string * name: string * decoder: Decoder<'TResult> -> (XmlElement -> Result<'TResult,DecodeError>)
val string: Decoder<string>

Type something to start searching.