使用Golang json.NewDecoder/json.NewEncoder

使用Golang json.NewDecoder/json.NewEncoder,json,go,Json,Go,我是围棋迷,我想知道我在这里错过了什么。我希望使用dec.Decode循环json值,最终得到响应的映射。我得到的是整个json字符串,作为映射的第一个元素的键。我错过了什么 答复示例: 2015/03/02 10:03:16映射[错误:无效\u请求错误\u描述:这不是可识别的WePay API调用错误\u代码:1001]映射[字符串]接口{} package main import ( "encoding/json" "io" "log" "net/http"

我是围棋迷,我想知道我在这里错过了什么。我希望使用
dec.Decode
循环json值,最终得到响应的映射。我得到的是整个json字符串,作为映射的第一个元素的键。我错过了什么

答复示例:

2015/03/02 10:03:16映射[错误:无效\u请求错误\u描述:这不是可识别的WePay API调用错误\u代码:1001]映射[字符串]接口{}

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))
}

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,
}

你能给我们看一个示例,或者返回的json的结构吗?从我看到的,你显然有一个带有三个键的映射,
error
error\u description
error\u code
。只需打印
len(v)
v[“error\u code”]
。它一直在正确解码JSON。我将日志行读取为基本映射[“error\u description:那不是一个可识别的WePay API调用错误\u code:1001 error:invalid\u request”](键作为整个JSON字符串),而不是包含这3个值的映射。总之,我是个白痴;)如何从此接口检索单个值?@VinitGaikwad
result[“error”]。(string)
,其他类似