如何访问Go语言中嵌套结构体的元素?
Go JSON解析后无法访问嵌套结构体元素的解决方法
你定义的SitesDetails是切片类型(本质是[]struct{...}),解析JSON后得到的mdl是一个切片对象,因此不能直接通过mdl.ApplicationDefaults访问嵌套结构体,必须先定位到切片中的具体元素,再访问其字段。
解决代码示例
直接通过索引获取切片元素后访问嵌套字段,若切片包含多个元素,可通过range遍历处理:
func main() { str := `[{ "ApplicationDefaults": { "ApplicationPoolName": "DefaultAppPool", "EnabledProtocols": "http", "Attributes": "", "ChildElements": "", "ElementTagName": "", "IsLocallyStored": true, "Methods": null, "RawAttributes": "", "Schema": "" }, "Id": 1 }]` mdl := foo(str) // 访问切片第一个元素的ApplicationDefaults fmt.Println(mdl[0].ApplicationDefaults.ApplicationPoolName) // 输出 DefaultAppPool // 遍历切片所有元素 for _, site := range mdl { fmt.Println(site.ApplicationDefaults.ApplicationPoolName) fmt.Println(site.ID) } }
补充说明
你的JSON根节点是数组[{...}],因此用切片类型的SitesDetails解析是正确的。如果后续JSON根节点改为单个对象{...},则需要调整结构体定义为非切片类型:
// 修改后的非切片结构体定义 type SitesDetails struct { ApplicationDefaults struct { ApplicationPoolName string `json:"ApplicationPoolName"` EnabledProtocols string `json:"EnabledProtocols"` Attributes string `json:"Attributes"` ChildElements string `json:"ChildElements"` ElementTagName string `json:"ElementTagName"` IsLocallyStored bool `json:"IsLocallyStored"` Methods interface{} `json:"Methods"` RawAttributes string `json:"RawAttributes"` Schema string `json:"Schema"` } `json:"ApplicationDefaults"` Applications []string `json:"Applications"` Bindings []string `json:"Bindings"` ID int `json:"Id"` Limits struct { ConnectionTimeout string `json:"ConnectionTimeout"` MaxBandwidth int64 `json:"MaxBandwidth"` MaxConnections int64 `json:"MaxConnections"` MaxURLSegments int `json:"MaxUrlSegments"` Attributes string `json:"Attributes"` ChildElements string `json:"ChildElements"` ElementTagName string `json:"ElementTagName"` IsLocallyStored bool `json:"IsLocallyStored"` Methods interface{} `json:"Methods"` RawAttributes string `json:"RawAttributes"` Schema string `json:"Schema"` } `json:"Limits"` }
此时即可直接通过mdl.ApplicationDefaults访问嵌套字段。
内容的提问来源于stack exchange,提问作者user20732118
相关产品推荐
相关产品推荐

