json - 使用 Golang json.NewDecoder/json.NewEncoder

标签 json go

我对围棋完全是个菜鸟,我试图理解我在这里错过了什么。我期望使用 dec.Decode 来循环 json 值并最终得到响应的映射。我得到的是整个 json 字符串作为 map 第一个元素的键。我错过了什么?

响应示例:

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

最佳答案

Decoder 将立即解码整个 JSON 值(在本例中为错误对象),您不必在循环中调用它:

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

作为响应,您将获得与此 JSON 等效的 map :

{"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 - 使用 Golang json.NewDecoder/json.NewEncoder,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28814366/

相关文章:

string - 按照要求的格式在 go lang 中将 float 转换为 string 。

go - 速率限制功能 40/秒 "golang.org/x/time/rate"

go - 如何检查 Go 应用是否可构建?

java - JSON UTF-8 编码错误

javascript - 数据表从API获取JSON而不设置 "aaData"

JSON - 多行字符串输出的数组错误 Node js | Node 请求

java - 如何在Okhttp中通过传递对象来发出POST请求?

go - 使用反射检测零值

emacs - Emacs 有类似 go-eldoc-mode 的东西吗?

android - 在 Android 中的 Activity 之间传递数据(大 JSON 数据字符串)