duanba7498 2018-04-13 15:51
浏览 25
已采纳

无法从Json响应中获取1个对象

This question already has an answer here:

I am a beginner to Golang. Can you help me with call of function. Here is an example:

package main

import (
    "fmt"
    "net/http"
)

type Info struct {
    Name string  `json:"name"`
    Year float64 `json:"year,string"`
}

func (b *Base) GetInfo() (Info, error) {
    var resp Info
    path := "example.com"

    return resp, http.Get(path)
}

func main() {
    test, err := Base.GetInfo()
    fmt.Println(test, err)

}

Output:

{Name Bob Year 10}

How I can get only "Bob" ?

And If my response contains more objects example

{Name Bob Year 10}{Name Jane Year 2}.

How I can get only names? Didnt understand how to decode it or call.

</div>
  • 写回答

1条回答 默认 最新

  • doushi1900 2018-04-13 15:55
    关注

    Use . parameter to get name from resp like

    func main() {
        test, err := Base.GetInfo()
        fmt.Println(test.Name, err)
    }
    

    But if there are multiple fields. Then you should save them in array of struct Info as:

    func (b *Base) GetInfo() ([]Info, error) {
        var resp []Info
        path := "example.com"
        return resp, http.Get(path)
    }
    
    func main() {
        test, err := Base.GetInfo()
        fmt.Println(test[0].Name, err)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?