Golang 映射结构未按预期工作

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


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

}

除“小时”外,所有字段都被填充。


牧羊人nacy
浏览 71回答 1
1回答

慕码人2483693

可能是您要多次解码到同一个BusinessAddRequest变量中。请注意,当您的结构元素是切片或映射时,这不会很好地工作(这既适用于包,mapstructure也适用于encoding/json!)。始终使用一个空的新变量。如果重复发生在循环中,请在循环体中声明您解码到的变量(每次运行循环时它将是一个新副本)。package mainimport "encoding/json"import "fmt"import "github.com/mitchellh/mapstructure"/* (your struct declaration not quoting it to save space) */func main() {&nbsp; &nbsp; var i map[string]interface{}&nbsp; &nbsp; config := &mapstructure.DecoderConfig{&nbsp; &nbsp; &nbsp; &nbsp; TagName: "json",&nbsp; &nbsp; }&nbsp; &nbsp; plan, _ := ioutil.ReadFile("zzz")&nbsp; &nbsp; var data []interface{}&nbsp; &nbsp; /*err :=*/ json.Unmarshal(plan, &data)&nbsp; &nbsp; for j := 0; j < len(data); j++ {&nbsp; &nbsp; &nbsp; &nbsp; i = data[j].(map[string]interface{})&nbsp; &nbsp; &nbsp; &nbsp; var x BusinessAddRequest /* declared here, so it is clean on every loop */&nbsp; &nbsp; &nbsp; &nbsp; config.Result = &x&nbsp; &nbsp; &nbsp; &nbsp; decoder, _ := mapstructure.NewDecoder(config)&nbsp; &nbsp; &nbsp; &nbsp; decoder.Decode(i)&nbsp; &nbsp; &nbsp; &nbsp; fmt.Printf("%+v\n", x)&nbsp; &nbsp; }}(请注意,我必须使用 DecoderConfig withTagName="json"才能使用您的结构定义,它被标记为 with"json:"和 not "mapstructure:")。如果这没有帮助,请检查您自己的代码并尝试找到一个类似于我在此处发布的重现您的问题的最小示例并将其添加到问题中。
打开App,查看更多内容
随时随地看视频慕课网APP