【发布时间】:2019-12-01 21:32:59
【问题描述】:
我正在尝试构建一个 F# Asp.Net Core 3.0 Web API,我在其中发送一些 F# 记录。
据我所知,Asp.Net Core 3.0 默认使用System.Text.Json 将对象序列化为 json。
为了使域模型自我记录,我使用了 F# 区分联合类型。
模型看起来像这样:
type Starttime =
| NotStarted
| Started of DateTime
type Category = {
Name: string
Starttime: Starttime
}
type ValueId = ValueId of String
type Value = {
Id: ValueId
Category: Category
}
所以我有一种联合类型,只有一种可能性ValueId,我有一种联合类型,有两种可能性Starttime,NotStarted 和Started,其中包含一个DateTime 对象。
现在我在我的控制器中构建一些示例数据并将其返回。
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 }
}
|]
当我查看json 返回的数据时,我得到了单选项联合类型(Guid)的数据,但我从未得到多选项联合类型的值。
[
{
"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
}
}
}
]
有谁知道如何发送多值联合类型的值? 还是将有区别的联合类型映射到匿名记录通常更好?
谢谢!
【问题讨论】:
标签: asp.net-core f# asp.net-core-webapi union-types system.text.json