使用Golang json.NewDecoder / json.NewEncoder

时间:2015-03-02 16:11:46

标签: json go

我去了一个总菜鸟,我正在努力去理解我在这里缺少的东西。我期望使用dec.Decode循环json值并最终得到响应的映射。我得到的是整个json字符串作为地图第一个元素的关键。我错过了什么?

回复示例:

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 个答案:

答案 0 :(得分:2)

Decoder会一次解码整个JSON值(在这种情况下是错误对象),你不必在循环中调用它:

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

作为回复,您会获得与此JSON

等效的地图
{"error":"invalid_request","error_description":"that is not a recognized WePay API call","error_code":1001}

结果:

map[string]interface{} {
    "error":"invalid_request",
    "error_description":"that is not a recognized WePay API call",
    "error_code":1001,
}