1
假設有一個數據類型JSON嵌套序列
它有一個對應的JSON視圖
例如V { a = 1, x = 2, y = 3 }
需要序列像
{
"a": 1,
"nested": {
"x": 2,
"y": 3
}
}
會是什麼樣ToJSON
例如像在這種情況下?
我已經試過:
instance ToJSON V where
toEncoding (V a b c) =
pairs ( "a" .= a
<> ("nested" .= pairs ("x" .= x <> "y" .= y))
)
<interactive>:6:10: error:
• No instance for (GHC.Generics.Generic V)
arising from a use of ‘aeson-1.1.1.0:Data.Aeson.Types.ToJSON.$dmtoJSON’
• In the expression:
aeson-1.1.1.0:Data.Aeson.Types.ToJSON.$dmtoJSON @V
In an equation for ‘toJSON’:
toJSON = aeson-1.1.1.0:Data.Aeson.Types.ToJSON.$dmtoJSON @V
In the instance declaration for ‘ToJSON V’
<interactive>:6:68: error:
• No instance for (ToJSON Encoding) arising from a use of ‘.=’
• In the second argument of ‘(<>)’, namely
‘("nested" .= pairs ("x" .= x <> "y" .= y))’
In the first argument of ‘pairs’, namely
‘("a" .= a <> ("nested" .= pairs ("x" .= x <> "y" .= y)))’
In the expression:
pairs ("a" .= a <> ("nested" .= pairs ("x" .= x <> "y" .= y)))
<interactive>:6:87: error:
• No instance for (ToJSON (V -> Int)) arising from a use of ‘.=’
(maybe you haven't applied a function to enough arguments?)
• In the first argument of ‘(<>)’, namely ‘"x" .= x’
In the first argument of ‘pairs’, namely ‘("x" .= x <> "y" .= y)’
In the second argument of ‘(.=)’, namely
‘pairs ("x" .= x <> "y" .= y)’
(0.01 secs,)
不錯,那'toEncoding'? –
@ДМИТРИЙМАЛИКОВ我已經更新了答案。 – Shersh