如何访问嵌套结构的元素

huangapple go评论127阅读模式
英文:

How to reach nested struct elements

问题

我有一个这样的结构体。我想将我的 JSON 解析为这个结构体,但我无法访问嵌套的结构体。

我期望能够像这样访问子结构体,但我不能:

func main() {
	str := `[{
		"ApplicationDefaults":  {
			"ApplicationPoolName": "DefaultAppPool",
     			....
	}]`

	mdl := foo(str)

	// mdl.ApplicationDefaults ?? 我无法像这样访问。只有一些函数可用,如:append!、last!、print!、range!、reverse!、sort!、var!
}

有人可以帮忙吗?

我的结构体:

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"`
}

这是我用于将 JSON 解析为结构体的代码:

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
}
英文:

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
}

答案1

得分: 2

你在这里进行了**slice**的解组(因为你的SitesDetails类型是[]struct,而你的JSON以数组开始),所以你应该能够通过以下方式访问你的详细信息:

poolName := model[0].ApplicationDefaults.ApplicationPoolName

这也解释了为什么你的IDE只建议可以应用于切片的操作,比如追加(我猜这会插入适当的代码来追加到你的切片中)。

顺便说一下,你真的不应该将变量命名为model,因为这显然是你用于包的名称(你使用了model.SitesDetails),所以在那一点上,你的变量名会遮蔽包 - 这可能会在后面引起很大的混淆,任何好的IDE都应该警告你这一点。

英文:

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.

huangapple
  • 本文由 发表于 2023年3月16日 19:20:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/75755556.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定