dongmisa4779 2015-03-02 16:11
浏览 807
已采纳

使用Golang json.NewDecoder / json.NewEncoder

I'm a total noob at go and I'm trying to understand what I'm missing here. I'm expecting to use dec.Decode to loop over the json values and end up with a map of the response. What I'm getting is the entire json string as the key to the first element of the map. What am I missing?

Example response:

2015/03/02 10:03:16 map[error:invalid_request error_description:that is not a recognized WePay API call error_code:1001] map[string]interface {}

package main

import (
    "encoding/json"
    "io"
    "log"
    "net/http"
    "reflect"
)

func main() {
    var v map[string]interface{}
    resp, err := http.Get("https://wepayapi.com/v2/")
    if err != nil {
        log.Println("Error: " + err.Error())
    }   
    defer resp.Body.Close()

    // resp.Body is an io.ReadCloser... NewDecoder expects an io.Reader
    dec := json.NewDecoder(resp.Body)

    // Decode reads the next JSON-encoded value from its input and stores it in the value pointed to by v.
    for err := dec.Decode(&v); err != nil && err != io.EOF; {
        log.Println("ERROR: " + err.Error())
        return
    }   
    log.Println(v, reflect.TypeOf(v))
}
  • 写回答

1条回答 默认 最新

  • douping4436 2015-03-02 16:30
    关注

    Decoder will decode the whole JSON value at once (in this case the error object), you don;y have to call it in a loop:

    if err := dec.Decode(&v); err != nil {
        log.Println("ERROR: " + err.Error())
        return
    }
    

    As a response you get a map equavalent of this JSON:

    {"error":"invalid_request","error_description":"that is not a recognized WePay API call","error_code":1001}
    

    Result:

    map[string]interface{} {
        "error":"invalid_request",
        "error_description":"that is not a recognized WePay API call",
        "error_code":1001,
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 onvif+openssl,vs2022编译openssl64
  • ¥15 iOS 自定义输入法-第三方输入法
  • ¥15 很想要一个很好的答案或提示
  • ¥15 扫描项目中发现AndroidOS.Agent、Android/SmsThief.LI!tr
  • ¥15 怀疑手机被监控,请问怎么解决和防止
  • ¥15 Qt下使用tcp获取数据的详细操作
  • ¥15 idea右下角设置编码是灰色的
  • ¥15 全志H618ROM新增分区
  • ¥15 在grasshopper里DrawViewportWires更改预览后,禁用电池仍然显示
  • ¥15 NAO机器人的录音程序保存问题