Golang mapstructure不能按预期工作

3

我试图将一个 map[string]interface{} 解码到一个结构体中,但是“hours”字段没有被填充。我正在使用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
}

除了"hours"字段外,所有字段都会被填充。
1个回答

7

可能是您多次解码到同一个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)
    }
}

注意,我必须使用一个带有TagName="json"的DecoderConfig才能使用您的结构定义,该定义被标记为"json:"而不是"mapstructure:"
如果这不能帮助您,请检查您自己的代码并尝试找到一个类似于我在此处发布的最小示例来重现您的问题,并将其添加到问题中。

非常感谢。我正在读取一个JSON文件并将其解组到接口中。我得到了一系列接口,然后通过循环遍历该系列并使用y:= s.Index(i)。Interface()。(map[string]interface {})将其转换为map[string]interface {}。我认为在这样做时我失去了结构。有更好的方法吗? - Pramod Shashidhara
我不确定我理解了这个问题。您要反序列化成什么,它怎么可能是接口的切片?(输入是JSON对象,因此无法反序列化为切片)。 - Leo K
好的,以下是读取文件并转换为映射的代码:plan:=ioutil.ReadFile(fileName) var data interface{} err := json.Unmarshal(plan, &data) s := reflect.ValueOf(data) for i := 0; i < s.Len(); i++ { y := s.Index(i).Interface().(map[string]interface{}) ... - Pramod Shashidhara
此外,文件具有一个JSON对象数组。 - Pramod Shashidhara
这应该可以工作。但是...请记住,解码器(包括mapstructure和encoding/json的解码器!!)不会清理您解码到的数据结构。如果您重复使用相同的“BusinessAddRequest”变量进行解码,则结果可能与您预期的不同。此外,最好不要使用reflect,除非没有其他方法-例如,如果您知道输入数据是数组,请将其解码为[]interface{}或(如果数组元素肯定是映射),直接解码为[]map[string]interface{}。我将更新答案以显示如何避免两次使用相同的变量。 - Leo K
谢谢。这个有效 :) 我认为将反序列化为interface{}而不是[]interface{}可能是问题所在。 - Pramod Shashidhara

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接