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 关注
- 70 浏览
添加回答
举报