【发布时间】:2020-05-19 12:24:12
【问题描述】:
这是我第一次尝试使用 Aeson 进行 JSON 反序列化。我无法对所有域数据类型的通用解码函数进行类型检查,即使单个具体类型的相应解码函数确实有效。
这里是多态函数:
import qualified RIO.ByteString.Lazy as BL
import qualified Data.Aeson as J
import qualified Path.Posix as P
loadDomainData :: J.FromJSON dData => FC.AbsFilePath -> IO dData
loadDomainData filePath = do
fileContents <- readFileBinary $ P.toFilePath filePath
let
decData :: Maybe dData
decData = J.decode $ BL.fromStrict fileContents
case decData of
Just d -> return d
Nothing -> throwString ("Could not decode data file " <> P.toFilePath filePath)
在初始失败后,我为解码器的目标类型插入了类型注释,但无济于事。如果我尝试编译它,会出现以下类型检查错误:
• Could not deduce (J.FromJSON dData1)
arising from a use of ‘J.decode’
from the context: J.FromJSON dData
bound by the type signature for:
loadDomainData :: forall dData.
J.FromJSON dData =>
FC.AbsFilePath -> IO dData
at src/Persistence/File/ParticipantRepository.hs:44:1-64
Possible fix:
add (J.FromJSON dData1) to the context of
the type signature for:
decData :: forall dData1. Maybe dData1
• In the expression: J.decode $ BL.fromStrict fileContents
[..]
我错过了什么?感谢四位的任何见解!
【问题讨论】:
标签: json haskell typeclass aeson