Haskell 在JSON实例中使用数据类型名称
我试图为Haskell 在JSON实例中使用数据类型名称,haskell,aeson,Haskell,Aeson,我试图为FromJSONtypeclass编写一个通用实例。其思想是在解析JSON时使用数据类型名称。我认为GHC应该能够做到这一点,但到目前为止,我的尝试失败了。下面是使用Typeabletypeclass的最简单版本 data GetResponse a = GetResponse { getCode :: Int, getItem :: a } deriving (Show) instance (Typeable a, FromJSON a) => FromJSON (GetRes
FromJSON
typeclass编写一个通用实例。其思想是在解析JSON时使用数据类型名称。我认为GHC应该能够做到这一点,但到目前为止,我的尝试失败了。下面是使用Typeable
typeclass的最简单版本
data GetResponse a = GetResponse { getCode :: Int, getItem :: a } deriving (Show)
instance (Typeable a, FromJSON a) => FromJSON (GetResponse a) where
parseJSON =
withObject "GetResponse" $ \o -> do
getCode <- o .: "code"
getItem <- o .: toLower (pack typeName)
return GetResponse {..}
where
typeName = showsTypeRep (typeRep Proxy :: Proxy a) ""
我试着用泛型做同样的事情,但还是得到了同样的错误
完整代码:启用
ScopedTypeVariables
扩展,我可以编译这个示例。使用此扩展名,Proxy a
中的a
对应于实例声明中相同的a
[1 of 1] Compiling Main ( generics.hs, interpreted )
generics.hs:74:48: error:
• Could not deduce (Typeable a0) arising from a use of ‘typeRep’
from the context: (Typeable a, FromJSON a)
bound by the instance declaration at generics.hs:66:10-61
The type variable ‘a0’ is ambiguous
• In the first argument of ‘showsTypeRep’, namely
‘(typeRep (Proxy :: Proxy a))’
In the second argument of ‘($)’, namely
‘showsTypeRep (typeRep (Proxy :: Proxy a)) ""’
In the second argument of ‘($)’, namely
‘pack $ showsTypeRep (typeRep (Proxy :: Proxy a)) ""’