我如何为Maybe做ToJSON?

时间:2016-02-21 05:53:08

标签: haskell

我如何为Maybe做ToJSON?

data MyData = MyData {
  id :: Int,
  something :: Maybe String
}

instance ToJSON MyData where
  toJSON (MyData id something) =
    object ["id" .= id
      , "something" .= ???
    ]

1 个答案:

答案 0 :(得分:1)

您可以重复使用ToJSON的{​​{1}}实例。

Maybe a

正如the documentation建议的那样,您可以让编译器为您派生一个实例。派生的实例与上面的实例完全相同。

data MyData = MyData {
  id        :: Int,
  something :: Maybe String
}

instance ToJSON MyData where
  toJSON (MyData id something) =
    object ["id" .= id
      , "something" .= toJSON something
    ]