dongmisa4779
2015-03-02 16:11 阅读 475

使用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 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,
    }
    
    点赞 评论 复制链接分享

相关推荐