Haskell ADT with Ezon

I struggled with a simple ADT, trying to get it to go back and forth in JSON, but I was not lucky no matter how hard I tried to massage or modify the type. What am I missing?

When it compiles, I always get the same runtime error:

> let t = Fahrenheit
> fromJSON $ toJSON t
Error "when expecting a (), encountered Object instead"

Trying this just gives me "Nothing", presumably due to the same error: decode $ encode t

I tried to keep track of these sources, but I cannot get around this runtime error, no matter what I try: Haskell :: Aeson :: parsing ADT based on the value of the https://www.fpcomplete.com/user/Geraldus field / algebraic-data-types-adts-with-aeson

Here is one form of code that I use. At first I tried to use this as a type built into another type, but when it didn’t work, I added a “value” key to try to make parsing this easier (no luck).

data TemperatureType = Celsius
                     | Fahrenheit
                     deriving (Show,Read,Typeable,Data,Eq)

-- This doesn't work either
-- $(deriveJSON defaultOptions ''TemperatureType)

instance ToJSON TemperatureType where
   toJSON Fahrenheit = object [ "value" .= String "Fahrenheit" ]
   toJSON Celsius    = object [ "value" .= String "Celsius" ]

instance FromJSON TemperatureType where
    parseJSON (Object x) = toTemperatureType <$> x .: "value"

toTemperatureType :: Text -> TemperatureType
toTemperatureType "Fahrenheit" = Fahrenheit
toTemperatureType "Celsius"    = Celsius
+4
source share
1 answer

Haskell needs help from you about the type of result of your expression, since in the current call it is impossible to conclude:

> fromJSON $ toJSON t :: Result TemperatureType
+8
source

All Articles