登录
首页 >  Golang >  Go问答

Golang 映射结构出现问题

来源:stackoverflow

时间:2024-03-26 23:51:32 216浏览 收藏

在使用 `mapstructure` 库将 `map[string]interface{}` 解码为结构时,出现 `hours` 字段未填充的问题。原因在于重复解码到同一变量中,尤其是当结构元素为切片或映射时,会产生此问题。为解决此问题,需要在循环中使用空的新变量,确保每次循环运行时解码到的变量都是一个新副本。建议在循环体中声明解码到的变量,并使用 `mapstructure.DecoderConfig` 配置 `TagName` 为 `"json"`。

问题内容

我正在尝试将 map[string]interface{} 解码为结构,但“小时”字段未填充。我正在使用 https://github.com/mitchellh/mapstruct 进行解码。这是结构:

businessaddrequest struct {
        name       string `json:"name"`
        phone      string `json:"phone"`
        website    string `json:"website,omitempty"`
        street     string `json:"street"`
        city       string `json:"city"`
        postalcode string `json:"postalcode"`
        state      string `json:"state"`
        hours []struct {
            day                 string `json:"day"`
            opentimesessionone  string `json:"open_time_session_one,omitempty"`
            closetimesessionone string `json:"close_time_session_one,omitempty"`
            opentimesessiontwo  string `json:"open_time_session_two,omitempty"`
            closetimesessiontwo string `json:"close_time_session_two,omitempty"`
        } `json:"hours"`
        cuisine []string `json:"cuisine,omitempty"`
        businessid int `json:"businessid,omitempty"`
        addressid  int `json:"addressid,omitempty"`
        userid     int `json:"userid,omitempty"`
}

这是示例数据:

{
    "name": "Agave ...",
    "phone": "(408) 000-000",
    "street": "Abcd",
    "city": "San",
    "postalCode": "90000",
    "state": "CA",
    "hours": [
      {
        "day": "monday",
        "open_time_session_one": "10:00",
        "close_time_session_one": "21:00"
      }
    ],
    "cuisine": [
      "Mexican, tacos, drinks"
    ],
    "userId": 1
}

除“小时”之外的所有字段均已填充。


解决方案


您可能会多次解码到同一个 businessaddrequest 变量中。请注意,当您的结构元素是切片或映射时,这不起作用(这既适用于 mapstruct 包,也适用于 encoding/json!)。始终使用空的新变量。如果重复发生在循环中,请在循环体中声明您解码到的变量(每次运行循环时它将是一个新副本)。

package main

import "encoding/json"
import "fmt"
import "github.com/mitchellh/mapstructure"

/* (your struct declaration not quoting it to save space) */

func main() {
    var i map[string]interface{}

    config := &mapstructure.DecoderConfig{
        TagName: "json",
    }

    plan, _ := ioutil.ReadFile("zzz")
    var data []interface{}
    /*err :=*/ json.Unmarshal(plan, &data)
    for j := 0; j < len(data); j++ {
        i = data[j].(map[string]interface{})
        var x BusinessAddRequest /* declared here, so it is clean on every loop */
        config.Result = &x
        decoder, _ := mapstructure.NewDecoder(config)
        decoder.Decode(i)
        fmt.Printf("%+v\n", x)
    }
}

(注意,我必须使用带有 tagname="json" 的 decoderconfig 才能使用您的结构定义,该结构定义用 "json:" 标记,而不是 "mapstruct:")。

如果这没有帮助,请检查您自己的代码,并尝试找到与我在此处发布的内容类似的最小示例,以重现您的问题并将其添加到问题中。

今天关于《Golang 映射结构出现问题》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

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