eeue56 / json-to-elm

Create Elm type aliases and decoders based on JSON input
http://json2elm.com
BSD 3-Clause "New" or "Revised" License
278 stars 23 forks source link

Union types generate incorrect code #19

Open avh4 opened 8 years ago

avh4 commented 8 years ago

This input

type InterestLevel
    = NotAtAllInteresting
    | NotVeryInteresting
    | Neutral
    | Interesting
    | VeryInteresting

yields

fromStringInterestLevel : InterestLevel -> Result String String
fromStringInterestLevel string = 
    case string of
        "Interesting" -> Result.Ok Interesting
        "Neutral" -> Result.Ok Neutral
        "NotAtAllInteresting" -> Result.Ok NotAtAllInteresting
        "NotVeryInteresting" -> Result.Ok NotVeryInteresting
        "VeryInteresting" -> Result.Ok VeryInteresting
        _ -> Result.Err ("Not valid pattern for decoder to InterestLevel. Pattern: " ++ (toString string))

decodeInterestLevel : Json.Decode.Decoder InterestLevel
decodeInterestLevel =
    Json.Decode.string `Json.Decode.andThen` fromStringInterestLevel

encodeInterestLevel : InterestLevel -> Json.Value
encodeInterestLevel =
 toString >> Json.Encode.string

which incorrectly has the type of fromStringInterestLevel : InterestLevel -> Result String String. It should be fromStringInterestLevel : String -> Result String InterestLevel.

Also, the generated code for decodeInterestLevel should be decodeInterestLevel = Json.Decode.customDecoder Json.Decode.string fromStringInterestLevel

andys8 commented 7 years ago

To use the union type I changes the result to have this format and the decoder type instead of Result:

fromStringSize : String -> Decoder Size
fromStringSize string =
    case string of
        "SizeLarge" ->
            Decode.succeed SizeLarge

        "SizeSmall" ->
            Decode.succeed SizeSmall

        _ ->
            Decode.fail ("Not valid pattern for decoder to Size. Pattern: " ++ toString string)