Skip to content

Commit

Permalink
Core: add json converters for F# types
Browse files Browse the repository at this point in the history
Implement JSON converters for F# Discriminated Union types
because System.Text.Json can't serialize them out of the box.
Without converters, got the following error:
```
System.NotSupportedException : F# discriminated union serialization is not supported. Consider authoring a custom converter for the type.
The unsupported member type is located on type 'FsharpExchangeDotNetStandard.Currency'. Path: $.Market.BuyCurrency.
```
  • Loading branch information
webwarrior-ws committed Feb 15, 2024
1 parent 2356027 commit 055624e
Showing 1 changed file with 30 additions and 1 deletion.
31 changes: 30 additions & 1 deletion src/FX.Core/RedisStorageLayer.fs
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,40 @@ open System
open FsharpExchangeDotNetStandard

open System.Text.Json
open System.Text.Json.Serialization
open StackExchange.Redis

[<AutoOpen>]
module Serialization =
let serializationOptions = JsonSerializerOptions.Default
// TODO: use FSharp.SystemTextJson for Discriminated Union support,
// in that case custom type converters are no longer needed
type SideTypeConverter() =
inherit JsonConverter<Side>()

override this.Read(reader, _typeToConvert, _options) =
reader.GetString() |> Side.Parse

override this.Write(writer, value, _options ) =
writer.WriteStringValue(value.ToString())

type CurrencyTypeConverter() =
inherit JsonConverter<Currency>()

override this.Read(reader, _typeToConvert, _options) =
match reader.GetString() with
| "BTC" -> BTC
| "USD" -> USD
| unknownCurrency -> failwithf "Unknown currency: %s" unknownCurrency

override this.Write(writer, value, _options ) =
writer.WriteStringValue(value.ToString())

let serializationOptions =
let options = JsonSerializerOptions()
options.Converters.Add(SideTypeConverter())
options.Converters.Add(CurrencyTypeConverter())
options


type OrderQuery =
{
Expand Down

0 comments on commit 055624e

Please sign in to comment.