This is useful if you use rust in the backend and elm on the front end
enum Complex{
Message(String),
Size(u64)
}
let c1 = Complex::Message("hi");
let c2 = Complex::Size(1024u64);
The encoded Json from rust will be:
c1:
{"variant": "Message",
"fields": ["hi"]
}
c2:
{"variant": "Size",
"fields": [1024]
}
The decoder in elm
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"
Usage: the data is requested from http rest api and the decoding of the payload will be
Http.fromJson complexDecoder payload
Decoding from string will be
Decode.decodeString complexDecoder payload