Pet*_*erB 2 serialization f# discriminated-union
如果我有:
type a = B | C
Run Code Online (Sandbox Code Playgroud)
如何编写静态成员 ToJson 和 FromJson?
我知道如何为记录类型编写它(如Chiron: JSON + Ducks + Monads的示例所示 ),但我找不到 DU 的任何示例。
编辑
在 s952163 有用的答案(以及后续评论)之后,我调整了代码以尝试使用选择 A | 的“简单”DU。B(而不是字符串的 A | ... 的 B)。我的代码现在是:
type SimpleDU =
| A
| B
static member ToJson (t : SimpleDU) =
match t with
| A -> Json.writeNone "a"
| B -> Json.writeNone "b"
static member FromJson (_ : SimpleDU) =
json {
let! duA = Json.tryRead "a"
match duA with
| Some s -> return s
| None -> return SimpleDU.B
}
Run Code Online (Sandbox Code Playgroud)
这可以编译,但是当我使用示例操作代码尝试它时:
let a = A
let b = B
let a2json = a |> Json.serialize
let (json2a:SimpleDU) = a2json |> Json.deserialize
let b2json = b |> Json.serialize
let (json2b:SimpleDU) = b2json |> Json.deserialize
Run Code Online (Sandbox Code Playgroud)
json2a 错误地返回 SimpleDU.B
A序列化为Object (map [("SimpleDU", String "a")])而不是的实现Object (map [("a", Null null)])是:
#I @"..\packages\Chiron.6.1.0\lib\net40"
#I @"..\packages\Aether.8.1.2\lib\net35"
#r "Chiron.dll"
#r "Aether.dll"
open Chiron
type SimpleDU =
| A
| B
static member ToJson x =
Json.write "SimpleDU" <|
match x with
| A -> "a"
| B -> "b"
static member FromJson(_ : SimpleDU) =
json {
let! du = Json.tryRead "SimpleDU"
match du with
| Some "a" -> return A
| Some "b" -> return B
| Some x -> return! Json.error <| sprintf "%s is not a SimpleDU case" x
| _ -> return! Json.error "Not a SimpleDU JSON"
}
// val serializedA : Json = Object (map [("SimpleDU", String "a")])
let serializedA = A |> Json.serialize
let serializedB = B |> Json.serialize
let (a : SimpleDU) = serializedA |> Json.deserialize
let (b : SimpleDU) = serializedB |> Json.deserialize
let aMatches = a = A
let bMatches = b = B
let serializedABBAA = [ A; B; B; A; A ] |> Json.serialize
let (abbaa : SimpleDU list) = serializedABBAA |> Json.deserialize
let abbaaMatches = abbaa = [ A; B; B; A; A ]
// allFine = true
let allFine = aMatches && bMatches && abbaaMatches
let defects =
Array [ Object <| Map.ofList [ ("SimpleDU", String "c") ]
Object <| Map.ofList [ ("Foo", String "bar") ] ]
// attempt = Choice2Of2 "Not a SimpleDU JSON"
let (attempt : Choice<SimpleDU list, string>) = defects |> Json.tryDeserialize
Run Code Online (Sandbox Code Playgroud)
您可以使用"a"and which来代替and来消除大小写,但我宁愿在 JSON 中拥有可读的大小写。"b"truefalseSome x
| 归档时间: |
|
| 查看次数: |
1104 次 |
| 最近记录: |