首页 > 解决方案 > 使用 mapstructure.Decode 将递归 []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": []
            }
        ]
    }
]

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

所以简而言之,[]Components struct可以是[]Components struct或空切片中的 Next 字段。因此,在查看互联网后,我发现您可以将[]interface{}as 字段用于struct[]切片或空切片。

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

components: <Components> (length: 1, cap: 4)
    [0]: <struct { Component, Inputs, InputErrors struct{}, ID string, Next []interface{} }>
        Component: Component
        Inputs: Inputs
        InputsErrors: struct{}
        ID: "dkjfjdkjfd"
        Next: []interface {} (length: 1, cap: 4)

并且该Next字段等于以下内容:

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

现在我想做以下步骤:

  1. 循环[]Components struct(在函数中)
  2. 如果是 next 则检查循环length == 0,如果是则中断循环,因为我们在最后。
  3. 循环遍历循环内的 Next 字段[]Component struct
  4. 设置一个名为 nextComponents 的新变量。
  5. mapstructure.decode(n, &nextComponents)mapstructure包中调用。
  6. []Components struct以作为参数递归调用循环nextComponents

小代码示例:

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{}结构。我认为我真的很接近,但我看不出我做错了什么,因为我没有收到任何错误,我不确定这是否是正确的方法。

欢迎任何建议或意见。谢谢你。:)

标签: gostructinterfacetype-conversion

解决方案


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


推荐阅读