FromJSON实例与DataKinds

时间:2016-12-17 18:37:06

标签: haskell aeson data-kinds

尝试使用TypeLits对数据类型执行JSON反序列化时,我遇到了以下问题:

Couldn't match type ‘n’ with ‘2’
      ‘n’ is a rigid type variable bound by
        the instance declaration at test.hs:14:10
      Expected type: aeson-0.11.2.1:Data.Aeson.Types.Internal.Parser
                       (X n)
        Actual type: aeson-0.11.2.1:Data.Aeson.Types.Internal.Parser
                       (X 2)

在以下示例中, FromJSON 实例中通常允许 Nat 的正确语法如何:

{-# LANGUAGE DataKinds #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE OverloadedStrings #-}

import GHC.TypeLits
import Data.Aeson
import Control.Monad (mzero)

data X (n :: Nat) where
  A :: Integer -> X 1
  B :: Integer -> X 2

instance FromJSON (X n) where
  parseJSON (Object o) = do
      v <- o .: "val"
      t <- o .: "type"
      case t of
        "a" -> return $ A v
        "b" -> return $ B v
  parseJSON _       = mzero

1 个答案:

答案 0 :(得分:3)

由于您显然无法知道要在编译时反序列化的类型,因此需要在存在主体中隐藏确切类型,然后通过模式匹配进行恢复。我通常使用通用的Some类型来隐藏幻像类型。

{-# LANGUAGE PolyKinds #-}

data Some (t :: k -> *) where
    Some :: t x -> Some t

现在您可以将实例编写为

instance FromJSON (Some X) where
    parseJSON (Object o) = do
        v <- o .: "val"
        t <- o .: "type"
        case (t :: String) of
          "a" -> return $ Some $ A v
          "b" -> return $ Some $ B v
    parseJSON _       = mzero

但是,您还需要启用FlexibleInstances扩展名。