我想我对框架的要求太多了。但只是想知道这是否可能。或者解决这个问题的方法。
新版本的 JSON.Net 开始支持 F# 联合类型。解决这个问题的方法是什么,意味着如果我使用的是 servicestack.text,那么我该如何展平联合类型以支持序列化。
这是两者的代码示例。
type Shape =
| Rectangle of width : float * length : float
| Circle of radius : float
| Empty
[<EntryPoint>]
let main argv =
// printfn "%A" argv
let shape1 = Rectangle(1.3, 10.0)
let json = JsonConvert.SerializeObject(shape1) //JSON.net
printfn "%A" json
// {
// "Case": "Rectangle",
// "Fields": [
// 1.3,
// 10.0
// ]
// }
let shape2 = JsonConvert.DeserializeObject<Shape>(json) //JSON.Net
printfn "%A" (shape2 = shape1) //true
let sJson = JsonSerializer.SerializeToString shape1 //SS.Text
printfn "%A" sJson
let sShape2 = JsonSerializer.DeserializeFromString sJson //SS.Text
printfn "%A" (sShape2 = shape1) //false
Console.Read() |> ignore
0 // return an integer exit code
使用 servicestack 的反序列化返回 false。与 JSON.net 相比,生成的 json 字符串也相当复杂。
如何为联合类型实现正确的序列化?