解析 Rust 列舉中的 JSON
如果在後端使用鏽,在前端使用 elm,這將非常有用
enum Complex{
Message(String),
Size(u64)
}
let c1 = Complex::Message("hi");
let c2 = Complex::Size(1024u64);
生鏽的編碼 Json 將是:
c1:
{"variant": "Message",
"fields": ["hi"]
}
c2:
{"variant": "Size",
"fields": [1024]
}
榆樹中的解碼器
import Json.Decode as Decode exposing (Decoder)
type Complex = Message String
| Size Int
-- decodes json to Complex type
complexDecoder: Decoder Value
complexDecoder =
("variant" := Decode.string `Decode.andThen` variantDecoder)
variantDecoder: String -> Decoder Value
variantDecoder variant =
case variant of
"Message" ->
Decode.map Message
("fields" := Decode.tuple1 (\a -> a) Decode.string)
"Size" ->
Decode.map Size
("fields" := Decode.tuple1 (\a -> a) Decode.int)
_ ->
Debug.crash "This can't happen"
用法:從 http rest api 請求資料,並且有效負載的解碼將是
Http.fromJson complexDecoder payload
從字串解碼將是
Decode.decodeString complexDecoder payload