I have struct like this. And I want to parse my Json to this struct. But I can not reach nested structs.
I was expecting to reach sub structs for like, but I can not:
func main() {
str := `[{
"ApplicationDefaults": {
"ApplicationPoolName": "DefaultAppPool",
....
}]`
mdl := foo(str)
// mdl.ApplicationDefaults ?? I can't reach like this. There are only a few functions like: append!, last! , print!, range!, reverse!, sort!, var!
}
Any one help?
My struct:
package model
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"`
}
This is the code that I use for parse json to my struct :
func foo(resp string) model.SitesDetails {
data := []byte(resp)
var m model.SitesDetails
err := json.Unmarshal(data, &m)
if err != nil {
log.Fatal(err)
}
return m
}
>Solution :
You’re unmarshalling into a slice here (as your SitesDetails type is a []struct and your json starts with an array), so you should be able to access your details via
poolName := model[0].ApplicationDefaults.ApplicationPoolName
This also explains why your IDE only suggests actions that can be applied to slices, such as appending (which I guess would insert the proper code to append to your slice).
By the way, you really shouldn’t call your variable model, as that’s the name your apparently using for your package as well (you’re using model.SitesDetails), so your variable name would shadow the package at that point – this could cause great confusion down the line and any decent IDE should warn you about that.