登录
首页 >  Golang >  Go问答

错误的解码自定义类型值时,mapstruct 会发生错误

来源:stackoverflow

时间:2024-03-13 11:36:28 186浏览 收藏

小伙伴们有没有觉得学习Golang很有意思?有意思就对了!今天就给大家带来《错误的解码自定义类型值时,mapstruct 会发生错误》,以下内容将会涉及到,若是在学习中对其中部分知识点有疑问,或许看了本文就能帮到你!

问题内容

我的应用程序采用 json 字符串,将其解组为结构 biggertype,然后使用 mapstructure 将结构的字段 settings 解码为类型 maintypebiggertype 需要支持多种类型的 settings,因此必须声明为 map[string]interface{}。该应用程序曾经工作正常,直到我们有一种新类型的 settings,即 maintype 包含一些类型为 specialtype 的自定义字段。

结构体和主要代码如下。运行代码会出现以下错误。

* 'b' expected a map, got 'string'

为简洁起见,删除了一些代码

package main

import (
    ...
    "github.com/mitchellh/mapstructure"
)

const myJSON = `{
  "settings": {
    "a": {
      "aa": {
        "aaa": {
          "sta": "special_object_A",
          "stb": "special_object_B"
        },
        "aab": "bab"
      },
      "ab": true
    },
    "b": "special_string"
  },
  "other": "other"
}`

func main() {
    var biggerType BiggerType

    err := json.Unmarshal([]byte(myJSON), &biggerType)
    if err != nil {
        panic(err)
    }

    var decodedMainType MainType

    if err := mapstructure.Decode(biggerType.Settings, &decodedMainType); err != nil {
        panic(err)
    }
}

type BiggerType struct {
    Other    string   `json:"other"`
    // Settings MainType `json:"settings"` can't be used as it needs to support other "Settings"
    Settings map[string]interface{} `json:"settings"`
}

type A struct {
    Aa *AA   `json:"aa"`
    Ab *bool `json:"ab"`
}

type AA struct {
    Aaa SpecialType `json:"aaa"`
    Aab string      `json:"aab"`
}

type MainType struct {
    A A           `json:"a"`
    B SpecialType `json:"b"`
}

type SpecialTypeObject struct {
    Sta string `json:"sta"`
    Stb string `json:"stb"`
}

func (s SpecialTypeObject) InterfaceMethod() (string, error) {
    return s.Sta + "+" + s.Stb, nil
}

type SpecialTypeString string

func (s SpecialTypeString) InterfaceMethod() (string, error) {
    return string(s), nil
}

type SpecialInterface interface {
    InterfaceMethod() (string, error)
}

// SpecialType SpecialTypeString | SpecialTypeObject
type SpecialType struct {
    Value SpecialInterface
}

func (s *SpecialType) UnmarshalJSON(data []byte) error {
    ...
}

我的目标是能够将 biggertype.settings 解码为 decodedmaintype ,并且所有值完好无损。任何人都可以与我分享任何解决方法或/和建议吗?

复制问题的演示:https://go.dev/play/p/g6mdnvoe2vz

谢谢。


正确答案


我同意 daniel farrell 的意见,但可以修复现有的解决方案。

这个想法是利用 mapstruct 的能力来定制其 decoder ,它可以在解码过程中的关键点调用一个“钩子”。有多个可用的钩子,它们可以组合成“链式”钩子。

由于有一个库存钩子能够检查目标变量的类型是否实现了 encoding.textunmarshaler,因此我们可以将 (*specialtype).unmarshaljson 调整为 (*specialtype).unmarshaltext,然后使用它: p>

func (s *specialtype) unmarshaltext(data []byte) error {
    if len(data) > 0 && data[0] != '{' {
        s.value = specialtypestring(data)
        return nil
    }

    var obj specialtypeobject
    if err := json.unmarshal(data, &obj); err != nil {
        return fmt.errorf("failed to unmarshal specialtype: %s", err)
    }
    s.value = obj
    return nil
}

var decodedmaintype maintype

msd, err := mapstructure.newdecoder(&mapstructure.decoderconfig{
    decodehook: mapstructure.textunmarshallerhookfunc(),
    result:     &decodedmaintype,
})
if err != nil {
    return biggertype{}, err
}

if err := msd.decode(biggertype.settings); err != nil {
    return biggertype{}, err
}

完整解决方案:https://go.dev/play/p/jaCD9FdSECz

但话又说回来,正如 daniel 暗示的那样,您似乎已经爱上了使用 mapstruct,因为它有望成为解决看似复杂问题的简单解决方案。
事实上, encoding/json 似乎有库存​​设施来覆盖您的用例 - 正是通过使某些类型实现 json.unmarshaler ,所以我会尝试在这种情况下放弃 mapstruct :它是一个有用的包,但现在您似乎是围绕其实现的框架规则进行工作。

为什么它不起作用

在 json 中,settings.b 是字符串类型。您已将其解码为 biggertype,其中设置是 map[string]interface{}。标准库提供的 json 解组过程会产生如下映射:

map[string]interface{} {
   "a": map[string]interface{}{...},
   "b": string("special_value"),
}

json 解码现已完成。程序中不再发生json解码。

然后,您尝试使用 mapstructsettings map 解码为 maintype,其中 b 的类型为 settingstype。因此 mapstruct.decode 尽职尽责地迭代您的 biggertype 并尝试将其转换为 maintype,但遇到了障碍。当到达b时,输入是字符串,输出是settingstype

您为设置类型编写了 unmarshaljson 函数,但 b 的值并未从 json 中解组 - 它已经是一个字符串。 decode 不知道如何将 string 转换为 specialtype (它说它期望 map 但这有点误导,如 it actually checks for map, struct, slice, and array types

重新表述您面临的问题

那么让我们更具体地识别错误:您有。 map[string]interface{} 带有字符串值,mapstruct.decode 尝试将其解码为带有 struct 值的结构体字段。

重新表述目标

您在此处显示的所有内容都是您的解决方案所面临的问题。你的根本问题是什么?您在 biggertype.settings 中有一个 interface{},它可能是 string,也可能是 map[string]interface{},并且您希望将其转换为包含 specialtypestringz 的 specialtype qbendczqb 或 specialtypeobj

不过,我不能完全将其与您的问题联系起来,您一直在谈论 maintype 可能是不同的类型,但程序中的所有不同类型似乎都在 specialtype 下。

如何解决

似乎这里显而易见的解决方案是放弃 mapstruct 并使用您已经用于 specialtype 的方法和自定义解组器。 mapstruct 对于需要解组 json 以内省某些属性,然后决定如何处理其他属性的情况非常有用。不过,您并没有对 mapstruct 做类似的事情;最接近的是您的自定义解组器。如果自定义 unmarshaller 可以完成这项工作,则您不需要 mapstruct

代码中的 specialtype.unmarshaljson 已经是如何将未知值包装在已知类型中并使用 switch 语句来处理未知值类型的示例。

所以只需抛弃 mapstruct,将 biggertype 重新定义为:

type BiggerType struct {
    Other    string   `json:"other"`
    Settings MainType `json:"settings"`
}

并让已经编写好的 unmarshaljson 处理 maintype.b

如果不是 specialtype 需要此逻辑,而是 maintype,则对 specialtype 执行与 maintype 相同的操作。

https://go.dev/play/p/DW8N8t3Lr0l

如果您想查看使用 mapstructy 的解决方案,请提供多个 json 输入示例,以便我了解它们有何不同以及为什么可能需要 mapstructy

终于介绍完啦!小伙伴们,这篇关于《错误的解码自定义类型值时,mapstruct 会发生错误》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>