我如何为Maybe做ToJSON?
data MyData = MyData {
id :: Int,
something :: Maybe String
}
instance ToJSON MyData where
toJSON (MyData id something) =
object ["id" .= id
, "something" .= ???
]
答案 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
]