purescript-argonaut-generic gDecodeJson: 'tag' 属性 丢失”

purescript-argonaut-generic gDecodeJson: 'tag' property is missing"

我正在学习 Argonaut,我能够手动解码 json:

foo = """{"f":"xxx"}"""
newtype Foo =
  Foo {
    f :: String
  }
derive instance genericFoo :: Generic Foo
instance decodeJsonFoo :: DecodeJson Foo where
  decodeJson json = do
    obj <- decodeJson json
    f <- obj .? "f"
    pure $ Foo { f }
main = either log (\x -> log $ show $ decodeJson x :: Either String Foo) (jsonParser foo)

我想改用泛型,我想

instance decodeJsonFoo :: DecodeJson Foo where
  decodeJson = gDecodeJson

会起作用。

然而,我得到了(Left "When decoding a Main.Foo: 'tag' property is missing")

看过 Generic.purs 但我是泛型的新手,无法理解。

我是不是误解了什么或者我该如何解决这个问题?

尝试使用 gEncodeJson 编码 Foo { f: "xxx" } - 您会看到输出格式包含 tag 属性,这就是解码器所抱怨的。

通用 encode/decode 当您将它作为应用程序的序列化格式时最有用,对于这种情况,如果您有从其他地方提供的 Foo 值,最好编写自己编解码器。