在JSON实例中使用数据类型名称

时间:2017-10-09 11:42:06

标签: haskell aeson

我正在尝试为FromJSON类型类编写一个通用实例。我们的想法是在解析JSON时使用数据类型名称。我认为这是GHC应该能做的事情,但到目前为止我的尝试都失败了。使用Typeable类型类的最简单版本如下所示。

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) ""

无法使用以下错误进行编译:

[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)) ""’

我尝试用Generics做同样的事情,但又得到了同样的错误。

完整代码:http://codepad.org/Gh3ifHkP

1 个答案:

答案 0 :(得分:3)

启用ScopedTypeVariables扩展我能够编译此示例。使用此扩展程序,a中的Proxy a对应于实例声明中的相同a