亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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 關注
  • 114 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號