登录
首页 >  Golang >  Go问答

使用MapStruct将嵌套的interface{}解码为struct{}时,返回nil?

来源:stackoverflow

时间:2024-02-21 10:18:22 382浏览 收藏

在Golang实战开发的过程中,我们经常会遇到一些这样那样的问题,然后要卡好半天,等问题解决了才发现原来一些细节知识点还是没有掌握好。今天golang学习网就整理分享《使用MapStruct将嵌套的interface{}解码为struct{}时,返回nil?》,聊聊,希望可以帮助到正在努力赚钱的你。

问题内容

我正在开发一个项目,我需要使用一个结构,其中一个字段(下一个)递归地使用相同的结构。原因是我用于解析的 json 数据来自流程图,其中连接了以下后续步骤。

我必须遵循以下结构:

type component struct {
    title string `json:"title"`
    name  string `json:"name"`
}

type inputs struct {
    vmname          string `json:"vmname"`
    serverrole      string `json:"serverrole"`
    os              string `json:"os"`
    appsearch       string `json:"appsearch"`
    platform        string `json:"platform"`
    location        string `json:"location"`
    msp             string `json:"msp"`
    zone            string `json:"zone"`
    networklot      string `json:"networklot"`
    frontendsubnet  string `json:"frontendsubnet"`
    cpu             string `json:"cpu"`
    memory          string `json:"memory"`
    storage         int    `json:"storage"`
    applicationname string `json:"applicationname"`
}

type components []struct {
    component   component `json:"component"`
    inputs      inputs    `json:"inputs"`
    inputerrors struct {
    } `json:"inputerrors"`
    id   string        `json:"id"`
    next []interface{} `json:"next"` //this could be a components []struct or []
}

我通过使用 json-to-go 转换器得到了这个结构,我在其中放入了以下 json:

[
    {
        "component": {
            "title": "title1",
            "name": "name1"
        },
        "inputs": {
            "serverrole": "server1",
            "os": "coolos",
            "platform": "platform",
            "location": "new york",
            "msp": "msp",
            "zone": "red",
            "networklot": "kavel",
            "frontendsubnet": "0.0.0.0/8080",
            "cpu": "2",
            "memory": "2",
            "vmname": "hola1",
            "appsearch": "ann",
            "storage": 0,
            "applicationname": "app1"
        },
        "inputerrors": {},
        "id": "uwlfqbijlijmqkocewdi",
        "next": [
            {
                "component": {
                    "title": "title1",
                    "name": "name2"
                },
                "inputs": {
                    "serverrole": "server2",
                    "os": "coolos2",
                    "platform": "platform",
                    "location": "amsterdam",
                    "msp": "msp",
                    "zone": "red",
                    "networklot": "kavel",
                    "frontendsubnet": "0.0.0.0/8081",
                    "cpu": "4",
                    "memory": "4",
                    "vmname": "hola2",
                    "appsearch": "ann",
                    "storage": 10,
                    "applicationname": "app2"
                },
                "inputerrors": {},
                "id": "1hzfllsx6t7b3q8iwcpx",
                "next": []
            }
        ]
    }
]

问题/或挑战在于 json 数据中的 "next" 以及 components 结构中相应的 next []interface{}。您可以在 json 数据中看到,第一个 next 包含另一个 json 数组,其数据结构与其父数组相同,但情况并非总是如此,因为您可以看到第二个 next 有一个空数组。这意味着不再有子进程,并且流程对其结束做出了反应。

因此,简而言之,[]components struct 中的 next 字段可以是 []components struct 或空切片。因此,在查看互联网后,我发现您可以使用 []interface{} 作为 struct[] 或空切片的字段。

接下来,我使用 json.unmarshal 将 json 数据解析为结构,在该结构中我得到以下正确结果:

components:  (length: 1, cap: 4)
    [0]: 
        component: component
        inputs: inputs
        inputserrors: struct{}
        id: "dkjfjdkjfd"
        next: []interface {} (length: 1, cap: 4)

其中 next 字段等于以下内容:

next <[]interface {}> (length: 1, cap: 4)
    [0] )
        data:  (length: 5)
            "component" )
            "inputs" )
            "inputerrors" )
            "id" )
            "next" )
                data: <[]interface {}> (length: 0, cap: 0) //when the length is 0 then the flow is at it's end.

现在我想执行以下步骤:

  1. 循环 []components struct(在函数中)
  2. 检查循环中是否下一个 length == 0,如果是,则中断循环,因为我们已经到了末尾。
  3. 循环 []component struct 循环内的 next 字段。
  4. 设置一个名为 nextcomponents 的新变量。
  5. 从 mapstructure 包中调用 mapstruct.decode(n, &nextcomponents)
  6. 使用 nextcomponents 作为参数,递归调用 []components struct 上的循环

小代码示例:

func DeployDiagram(input interface{}) map[int]types.NewSystemResponse { 
    components := input.(types.Components)
    for i, component := range components {
        //do some logic
        //...
        //...

        //1. check if next slice == 0 if so then break loop
        //2. loop over the next []interface to interface{}
        //3. convert interface{} to types.Components
        //4. DeployDiagram(types.Components) recursive call
        if len(component.Next) == 0 {
            break //we are in the last object from the diagram no more next objects.
        }

        for _, n := range component.Next {
            var nextComponents types.Components
            mapstructure.Decode(n, &nextComponents) //this end's up being nil?
            DeployDiagram(nextComponents)
        }
    }

    return someThing
}

问题是 nextcomponents 返回 nil,而它应该返回一个新的 []components{} 结构。我认为我真的很接近,但我看不到我做错了什么,因为我没有收到任何错误,而且我不确定这是否是正确的方法。

欢迎任何建议或建议。谢谢。 :)


正确答案


Go 中的 json 解析器不区分空数组和填充数组。你可以使用Components代替[]interface{},即使json数组中没有任何内容,它也会很好地解析它。

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

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