解析 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