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

使用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 使用MATLAB进行余弦相似度计算加速
  • ¥15 服务器安装php5.6版本
  • ¥15 我想用51单片机和数码管做一个从0开始的计数表 我写了一串代码 但是放到单片机里面数码管只闪烁一下然后熄灭
  • ¥20 系统工程中,状态空间模型中状态方程的应用。请猛男来完整讲一下下面所有问题
  • ¥15 我想在WPF的Model Code中获取ViewModel Code中的一个参数
  • ¥15 arcgis处理土地利用道路 建筑 林地分类
  • ¥20 使用visual studio 工具用C++语音,调用openslsx库读取excel文件的sheet问题
  • ¥100 寻会做云闪付tn转h5支付链接的技术
  • ¥15 DockerSwarm跨节点无法访问问题
  • ¥15 使用dify通过OpenAI 的API keys添加OpenAI模型时报了“Connection Error”错误