douwen1549 2018-01-03 16:40 采纳率: 100%
浏览 4
已采纳

使用Golang将响应映射到结构

I am attempting to map a response from an API to a struct using Golang.

The JSON that comes back when I view the link in the browser is below:

{
"GBP": 657.54
}

And I just want to map it to a simple struct like so:

type Price struct {
    Name  string
    Value float64
}

Here is my current code.

func FetchCoinPrice(fsym string, tsyms string) Price {
    url := fmt.Sprintf("https://min-api.cryptocompare.com/data/price?fsym=" + fsym + "&tsyms=" + tsyms)

    fmt.Println("Requesting data from " + url)

    price := Price{}

    // getting the data using http
    request, err := http.Get(url)
    if err != nil {
        log.Fatal(err.Error())
    }

    // Read the response body using ioutil
    body, err := ioutil.ReadAll(request.Body)
    if err != nil {
        log.Fatal(err.Error())
    }

    defer request.Body.Close()

    if request.StatusCode == http.StatusOK {
        json.Unmarshal(body, &price)
    }

    return price

}

At the moment all I receive is an empty struct, I know the link is bringing back the correct data and I've tested it in my browser.

  • 写回答

2条回答 默认 最新

  • dtu1747 2018-01-03 16:46
    关注

    The mapping doesn't work that way. Instead, you should use a map:

        data := []byte(`{
           "GBP": 657.54
         }`)
    
        priceMap := map[string]float64{}
        err := json.Unmarshal(data, &priceMap)
        // Check your errors!
        if err != nil {
          log.Fatal(err.Error())
        }
        fmt.Println(priceMap)
    

    This will print:

    map[GBP:657.54]
    

    You can then iterate over the map and build the struct you mentioned above, or just access the entry directly if you know the currency. eg: priceMap["GBP"]

    You should really check your errors, especially if you're not getting the output you expect from Unmarshal.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置