为了账号安全,请及时绑定邮箱和手机立即绑定

Golang 映射结构未按预期工作

Golang 映射结构未按预期工作

Go
牧羊人nacy 2023-03-21 14:47:53
我正在尝试将 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}除“小时”外,所有字段都被填充。
查看完整描述

1 回答

?
慕码人2483693

TA贡献1860条经验 获得超9个赞

可能是您要多次解码到同一个BusinessAddRequest变量中。请注意,当您的结构元素是切片或映射时,这不会很好地工作(这既适用于包,mapstructure也适用于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)

    }

}

(请注意,我必须使用 DecoderConfig withTagName="json"才能使用您的结构定义,它被标记为 with"json:"和 not "mapstructure:")。


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


查看完整回答
反对 回复 2023-03-21
  • 1 回答
  • 0 关注
  • 70 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信