How to serialize F# discriminated union types in F# Asp Core Wep API

Viewed 1005

I´m trying to build a F# Asp.Net Core 3.0 Web API where I send some F# records. As far as I know Asp.Net Core 3.0 uses System.Text.Json by default to serailize objects to json. To make the domain model self documenting I use F# Discriminated Union Types.

The model looks like that:

type Starttime =
    | NotStarted
    | Started of DateTime

type Category = {
    Name: string
    Starttime: Starttime
}

type ValueId = ValueId of String

type Value = {
    Id: ValueId
    Category: Category
}

So I have one union type with just one possibility ValueId and I have one union type with two possibilities Starttime with NotStarted and Started which contains a DateTime object.

Now in my controller I build some sample data and return that.

let isStarted i : Starttime =
    if i % 2 = 0 then
        Started DateTime.Now
    else
        NotStarted

[<HttpGet>]
member __.Get() : Value[] = 
    [|
        for index in 1..2 ->
            { 
                Id = ValueId (Guid.NewGuid().ToString())
                Category = {
                    Name = sprintf "Category %i" index
                    Starttime = isStarted index }
            }
    |]

When i look at the data returned in json I get the data for the single option union type (the Guid) but I never get a value for the multi option union type.

[
  {
    "id": {
      "tag": 0,
      "item": "6ed07303-6dfa-42b4-88ae-391bbebf772a"
    },
    "category": {
      "name": "Category 1",
      "starttime": {
        "tag": 0,
        "isNotStarted": true,
        "isStarted": false
      }
    }
  },
  {
    "id": {
      "tag": 0,
      "item": "5e122579-4945-4f19-919c-ad4cf16ad0ed"
    },
    "category": {
      "name": "Category 2",
      "starttime": {
        "tag": 1,
        "isNotStarted": false,
        "isStarted": true
      }
    }
  }
]

Does anyone know how to also send the values for the multi value union type? Or is it generally better to map discriminated union types to anonymous records?

Thank you!

1 Answers

At the moment, System.Text.Json does not support F# types (there's an open issue about this here)

For now, you can use this library instead.

Related