Encoding Guide
While encoding is not really a big concern for STJ there's still types that are not supported out of the box. As usual... Discriminated unions are at the center of the stage here.
That being said, JDeck provides a way to encode values to JSON strings in a similar fashion to the decoders.
An Encoder is defined as:
type Encoder<'T> = 'T -> JsonNode
There's two styles offered currently by this library:
- Property list style
- Pipeline style
let propStyleEncoder =
Json.object [
"name", Encode.string "John Doe"
"age", Encode.int 42
("profile", Json.object [ "id", Encode.guid(Guid.NewGuid()) ])
]
The property list style is basically just a recollection of key-value pairs in a list.
let pipeStyleEncoder =
Json.empty()
|> Encode.property("name", Encode.string "John Doe")
|> Encode.property("age", Encode.int 42)
|> Encode.property(
"profile",
Json.empty() |> Encode.property("id", Encode.guid(Guid.NewGuid()))
)
The pipeline style is basically a "builder" like pattern where you start with an empty object and keep adding properties to it. Both styles are equivalent, and you can choose the one that fits your style better you can even mix and match both! though I wouldn't recommend that.
Let's see a more meaningful example, we'll encode a Person object. First let's define a couple of types to work with:
type Address = {
street: string
city: string
zip: string option
} with
static member Encoder: Encoder<Address> =
fun address ->
Json.object [
"street", Encode.string address.street
"city", Encode.string address.city
match address.zip with
| Some zip -> "zip", Encode.string zip
| None -> ()
]
It is recommended to define an encoder for whatever type you want to encode in order to keep your code less verbose in the main encoder.
type ContactMethod =
| Email of string
| Phone of string
static member Encoder: Encoder<ContactMethod> = fun contactMethod ->
Json.object [
match contactMethod with
| Email email ->
"type", Encode.string "email"
"value", Encode.string email
| Phone phone ->
"type", Encode.string "phone"
"value", Encode.string phone
]
As we've discussed in other sections of this website, discriminated unions are a particular type that needs special handling when working with System.Text.Json APIs as it is not supported.
Now let's define the Person type and its encoder:
type Person = {
name: string
age: int
address: Address
contactMethod: ContactMethod list
} with
static member Encoder: Encoder<Person> =
fun person ->
Json.object [
"name", Encode.string person.name
"age", Encode.int person.age
// here we use our previously defined encoders
"address", Address.Encoder person.address
// for each contact method we encode it using the ContactMethod encoder
"contactMethod", Json.sequence(person.contactMethod, ContactMethod.Encoder)
]
The defined encoder for the Person type uses the previously defined encoders for the Address and ContactMethod types. For other discriminated unions and custom types you can customize entirely the shape of the final JSON object.
let encodedPerson = Person.Encoder person
printfn $"%s{encodedPerson.ToJsonString()}"
The final JSON object will look like this:
|
The JSON object above has been formatted for display purposes, but the actual JSON string will be minified if no options are supplied to the ToJsonString
method.
The encoding story is not set in stone yet for JDeck, and there's still room for improvement, feedback is appreciated in this regard.
<summary>The base class that represents a single node within a mutable JSON document.</summary>
<summary>Provides functions for creating JSON nodes.</summary>
static member Json.object: values: (string * JsonNode) seq -> JsonObject
<summary>Provides functions for encoding values to JSON nodes.</summary>
[<Struct>] 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>
--------------------
Guid ()
Guid(b: byte array) : Guid
Guid(b: ReadOnlySpan<byte>) : Guid
Guid(g: string) : Guid
Guid(b: ReadOnlySpan<byte>, bigEndian: bool) : Guid
Guid(a: int, b: int16, c: int16, d: byte array) : Guid
Guid(a: int, b: int16, c: int16, d: byte, e: byte, f: byte, g: byte, h: byte, i: byte, j: byte, k: byte) : Guid
Guid(a: uint32, b: uint16, c: uint16, d: byte, e: byte, f: byte, g: byte, h: byte, i: byte, j: byte, k: byte) : Guid
val string: value: 'T -> string
--------------------
type string = String
val int: value: 'T -> int (requires member op_Explicit)
--------------------
type int = int32
--------------------
type int<'Measure> = int