我需要将类型的值转换为Distribution.PackageDescription.FlagName
带有包的 JSONText.JSON
对象json
。
我最终采用了以下方法:
instance JSON FlagName where
showJSON (FlagName n) = makeObj [ ("FlagName", showJSON n) ]
readJSON object = do
obj <- readJSON object
flag <- valFromObj "FlagName" obj
return flag
当我尝试对一个值进行编码并再次对其进行解码时,会发生以下情况:
> showJSON (FlagName "foo")
JSObject (JSONObject {fromJSObject = [("FlagName",JSString (JSONString {fromJSString = "foo"}))]})
> readJSON (showJSON (FlagName "foo")) :: Result FlagName
Error "Unable to read JSObject"
我猜错误就在那一行:obj <- readJSON object
如何强制 Haskell 使用实例中的readJSON
函数?JSON String
更新:我现在发现了一个相当老套的解决方案:
instance JSON FlagName where
showJSON (FlagName n) = makeObj [ ("FlagName", showJSON n) ]
readJSON object = do
obj <- readJSON (showJSON (FlagName "foo")) :: Result (JSObject JSValue)
let maybeFlagName = lookup "FlagName" $ fromJSObject obj
maybe (fail "Not a FlagName object") (\jsn -> liftM FlagName $ (readJSON jsn :: Result String)) maybeFlagName
如果有人提出更优雅的解决方案,我将不胜感激......