小细节:您引用两次:将对象地址的地址提供给json.Unmarshal。只需提供地址。
`
允许多行,无需拆分json输入。
我不知道您要在哪里尝试实现u.Details[Phone:"1111"].Email
,但这不是Go语法。你的Details
成员差得远Detail
。切片类似于数组,可以通过索引进行访问。
另外,您的json与您的对象结构不匹配。如果您要在一个内容中包含多个详细信息,则需要将其嵌入到数组([ ]
)中
您可以执行以下操作:(http://play.golang.org/p/OP1zbPW_wk)
package main
import (
"encoding/json"
"fmt"
)
type Content struct {
Owner string
Details []*Detail
}
type Detail struct {
Phone string
Email string
}
func (c *Content) SearchPhone(phone string) *Detail {
for _, elem := range c.Details {
if elem.Phone == phone {
return elem
}
}
return nil
}
func (c *Content) SearchEmail(email string) *Detail {
for _, elem := range c.Details {
if elem.Email == email {
return elem
}
}
return nil
}
func main() {
encoded := `{
"Owner": "abc",
"Details": [
{
"Phone": "1111",
"Email": "@gmail"
},
{
"Phone": "2222",
"Email": "@yahoo"
}
]
}`
// Decode the json object
u := &Content{}
if err := json.Unmarshal([]byte(encoded), u); err != nil {
panic(err)
}
// Print out Email and Phone
fmt.Printf("Email: %s\n", u.SearchPhone("1111").Email)
fmt.Printf("Phone: %s\n", u.SearchEmail("@yahoo").Phone)
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句