我试图将一个 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"字段外,所有字段都会被填充。
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 Shashidharareflect
,除非没有其他方法-例如,如果您知道输入数据是数组,请将其解码为[]interface{}
或(如果数组元素肯定是映射),直接解码为[]map[string]interface{}
。我将更新答案以显示如何避免两次使用相同的变量。 - Leo K