如何解决Haskell Aeson 返回空对象
如果不是nothing,我试图返回一个JSON数据表示,如果nothing则返回一个空的JSON对象;
我知道我可以做到:
encode ()
-- "[]"
但现在我想要一个空对象 ("{}"
)。
λ data Person = Person { id :: Integer,height :: Float } deriving (Show)
λ instance ToJSON Person where toJSON (Person { id = id,height = height }) = object [ "id" .= id,"height" .= height ]
λ encode (Person 1 72.8)
-- "{\"height\":72.8,\"id\":1}"
但最终没有 Person 将用 nothing 表示,如果我这样做 encode (nothing)
我得到一个错误:
<interactive>:11:1: error:
• Ambiguous type variable ‘a0’ arising from a use of ‘encode’
prevents the constraint ‘(ToJSON a0)’ from being solved.
Probable fix: use a type annotation to specify what ‘a0’ should be.
These potential instances exist:
instance ToJSON DotNetTime
-- Defined in ‘aeson-1.4.7.1:Data.Aeson.Types.ToJSON’
instance ToJSON Value
-- Defined in ‘aeson-1.4.7.1:Data.Aeson.Types.ToJSON’
instance (ToJSON a,ToJSON b) => ToJSON (Either a b)
-- Defined in ‘aeson-1.4.7.1:Data.Aeson.Types.ToJSON’
...plus 26 others
...plus 63 instances involving out-of-scope types
(use -fprint-potential-instances to see them all)
• In the expression: encode (nothing)
In an equation for ‘it’: it = encode (nothing)
解决方法
encode Nothing
将始终返回 null
。可以通过执行 encode (object [])
来对空对象进行编码。如果您想以这种方式对 Nothings
进行编码,您可以为这样的 Maybe
值编写一个自定义编码函数。
encodeMaybe :: ToJSON a => Maybe a -> ByteString
encodeMaybe (Just x) = encode x
encodeMaybe Nothing = encode (object [])
或者替代
toJSONMaybe :: ToJSON a => Maybe a -> Value
toJSONMaybe (Just x) = toJSON x
toJSONMaybe Nothing = object []
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。