dtvhqlc57127 2014-06-24 16:17
浏览 17
已采纳

Golang Json未返回期望值

I have a code @ http://play.golang.org/p/HDlJJ54YqW

I wanted to print the Phone and email of a person. It can be of multiple entries. But getting the error undefined. Can anyone help out.

Thanks.

  • 写回答

1条回答 默认 最新

  • doumei9832 2014-06-24 16:55
    关注

    Small details: you are referencing twice: you give the address of the address of the object to json.Unmarshal. Just give the address.

    ` allows for multiline, no need to split your json input.

    I don't know what you where trying to achieve with u.Details[Phone:"1111"].Email, but this is no Go syntax. your Details member is a slice off Detail. A slice is similar to an array and can be accessed by index.

    Also, your json does not match your object structure. If you want to have multiple details in one content, then it needs to be embed in an array ([ ])

    You could do something like this: (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
    ", u.SearchPhone("1111").Email)
        fmt.Printf("Phone: %s
    ", u.SearchEmail("@yahoo").Phone)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计