1 回答

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:")。
如果這沒有幫助,請檢查您自己的代碼并嘗試找到一個類似于我在此處發布的重現您的問題的最小示例并將其添加到問題中。
- 1 回答
- 0 關注
- 114 瀏覽
添加回答
舉報