从JSON到自定义数据类型

时间:2015-07-08 12:43:38

标签: json haskell

我有以下课程:

type ID = UUID

data MySubClass1 = MySubClass1
    { sVar1 :: UTCTime
    , sVar2 :: UTCTime
    }

data MyMainClass = MyMainClass
    { var1 :: ID
    , var2 :: MySubClass1
    , var3 :: (Int, String)
    , var4 :: Maybe String
    }

这是JSON本身:

{
  "var1" : ...,
  "var2_1": ...,
  "var2_2": ...,
  "var3_1": ...,
  "var3_2": ...,
  "var4": ...,

  "svar1": ...,
  "svar2": ...
}

我需要为他们创建JSON实例:

--OK
instance FromJSON MySubClass1 where
  parseJSON (Object v) = 
    MySubClass1 <$> v .: "svar1" 
           <*> v .: "svar2" 

--OK
instance ToJSON MySubClass1 where
  toJSON (MySubClass1 sVar1 sVar2) =
    object ["svar1" .= sVar1
      , "svar2" .= sVar2
    ]

这是我遇到的困难

instance FromJSON MyMainClass where
  parseJSON (Object v) = 
    MyMainClass <$> v .: "var1" 
           <*> (MySubClass1 v .: "var2_1" v .: "var2_2") -- error
           <*> (v .: "var3_1" v .: "var3_2") -- error
           <*> v .:? "var4" 

instance ToJSON MyMainClass where
  toJSON (MyMainClass var1 var2 var3 var4) =
    object ["var1" .= var1
      , "var2" .= ---???
      , -- what's next?
    ]

大多数错误都表示类型不匹配。

0 个答案:

没有答案