[英]How to create “ActionCtxT” in Spock?
我想從json對象中提取一個值。 我有這個:
post "/test" $ do
a <- jsonBody'
let b = show (a :: Object) -- works well
myVal <- (a :: Object) .: "some_key" -- error
text "test123"
錯誤:
• Couldn't match type ‘aeson-1.0.2.1:Data.Aeson.Types.Internal.Parser’
with ‘ActionCtxT () (WebStateM () MySession MyAppState)’
Expected type: ActionCtxT () (WebStateM () MySession MyAppState) a0
Actual type: aeson-1.0.2.1:Data.Aeson.Types.Internal.Parser a0
• In a stmt of a 'do' block:
myVal <- (a :: Aeson.Object) Aeson..: "some_key"
我知道這是什么意思:myVal的行必須返回ActionCtxT類型的內容以及所有其他行。 或純價值。 因此,如何解決呢?
jsonBody' :: (MonadIO m, FromJSON a) => ActionCtxT ctx m a
jsonBody'
為您提供了使用Aeson FromJSON
實例解析請求主體的方法。
通常,通過將JSON數據映射到自定義數據類型,然后為該數據類型提供FromJSON
實例,可以更輕松地使用Aeson。
解釋示例,您可以在Aeson文檔中找到,如果您的JSON看起來像這樣:
{ "name": "Joe", "age": 12 }
然后,您可以創建一個數據類型:
data Person = Person {
name :: Text
, age :: Int
} deriving Show
並手動創建FromJSON實例:
{-# LANGUAGE OverloadedStrings #-}
instance FromJSON Person where
parseJSON (Object v) = Person <$>
v .: "name" <*>
v .: "age"
-- A non-Object value is of the wrong type, so fail.
parseJSON _ = empty
您可以選擇從數據類型自動派生FromJSON實例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.