json - 如何在 Go 中通过 http 解码 JSON 检索

标签 json go

我正在访问一个以以下形式返回 JSON 的 API:

[{"UniqueID":1234, "DocID":5678}, {"UniqueID":5678, "DocID":9101112}]

此 API 是用 Go 编写的,示例输出是返回值在浏览器中的显示方式。内容类型 header 是 application/json

我有以下代码来检索和解码:

    type UniqueIDDocID struct{
        UniqueID int64 `json: "UniqueID"`
        DocID int64 `json: "DocID"`
    }
    type UniqueIDDocIDCollection struct{
        FullList []UniqueIDDocID
    }

    func retrieveUniqueIDByPublication(nodeid int64, publication string){
        // call the API
        //hgr := new(retrieval.HttpGetRetrieval)
// endpoint is defined here - I have removed for privacy reasons
        fmt.Println(endpoint) // the url which I know works
        /*response, err := hgr.RequestResponse(endpoint)
            if err != nil {
                l4g.Warn("Could not retrieve the endpoint %s. Error: ", endpoint, err)
                return
            }
            defer hgr.CloseResponse(response)
            queryResult := hgr.ReadResponse(response)*/
            client := new(http.Client)
            request, err := http.NewRequest("GET", endpoint, nil)
            if err != nil {
                l4g.Warn("Could not retrieve the endpoint %s. Error: %v", endpoint, err)
                return  
            }
            request.Header.Set("Content-Type", "applicaiton/json")
            response, err := client.Do(request)
            if err != nil {
                l4g.Warn("Could not retrieve the endpoint %s. Error: %v", endpoint, err)
                return  
            }
            defer response.Body.Close()
            var reader io.ReadCloser
            reader = response.Body
            defer reader.Close()
            queryResult, readErr := ioutil.ReadAll(reader)
            if err != nil {
                l4g.Warn("Could not retrieve the endpoint %s. Error: %v", endpoint, readErr)
                return  
            }
            if queryResult == nil {
                l4g.Warn("Nothing returned %s.", endpoint)
                return
            }


            var details UniqueIDDocIDCollection
        // process return
            if err:=json.Unmarshal(queryResult, &details); err != nil{
                l4g.Warn("Failed to unmarshall return %v from %s", queryResult, endpoint)
                return
            }
            writeUniqueIDFile(details)
    }

我收到“解码失败”消息,日志中的详细信息显示如下:

[91 123 34 85 110 105 113 117 101 73 68 34 58 34 56 51     57 51 50 53 56 54 34 44 34 68 111 99 73 68 34 58 52 49 50 49 54 57 49 57 125 44 123 34 85 110 105 113 117 101]

作为代表性样本。

我在这个解码步骤中做错了什么?

我想要的输出是 UniqueIDDocIDCollection 结构上有一个 slice ,其中包含类型为 UniqueIDDocID 的项目,然后我可以从中获取 UniqueID 并将其写入一个以行分隔的文件。

我一直在谷歌上搜索并尝试了很多方法,但每次都是这样。

如果您对源 JSON 也有任何建议,请分享这些建议,因为我可能会在 API 中进行更改。

提前感谢您的帮助 弥敦道

最佳答案

错误数据是一个[]byte slice;如果将它打印到 %s (fmt.Printf("foo: %s\n", foo)) 或任何你拥有它的地方,你可能会得到更有用的东西,现在将它包装在 字符串(foo)

我为您的 Unmarshall 做了一个更简单的示例,它似乎工作正常。我怀疑问题到底出在输入数据上吗?

package main

import (
    "encoding/json"
    "log"
)

type UniqueIDDocID struct {
    UniqueID int64 `json: "UniqueID"`
    DocID    int64 `json: "DocID"`
}
type UniqueIDDocIDCollection struct {
    FullList []UniqueIDDocID
}

const INPUT = `[{"UniqueID":1234, "DocID":5678}, {"UniqueID":5678, "DocID":9101112}]`

func main() {

    coll := new(UniqueIDDocIDCollection)

    err := json.Unmarshal([]byte(INPUT), &coll.FullList)

    if err != nil {
        log.Printf("Could not unmarshall %s: %s", INPUT, err)
    }

    log.Printf("Now have data: %#v\n", coll)

}

输出(try it on play.golang)

Now have data: &main.UniqueIDDocIDCollection{FullList:[]main.UniqueIDDocID{main.UniqueIDDocID{UniqueID:1234, DocID:5678}, main.UniqueIDDocID{UniqueID:5678, DocID:9101112}}}

首先将“解码失败”错误消息中的 %v 更改为 %s;也许您没有您期望的数据。您还应该包括从 json.Unmarshall 返回的错误,它可能会告诉您出了什么问题。 :-)

关于json - 如何在 Go 中通过 http 解码 JSON 检索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17815364/

相关文章:

java - 需要开发基于图形的模拟引擎的建议

go - 在远程机器上执行WQL查询

mysql - 根据 slice Go中的键顺序对数据进行排序

string - 如何将字符串转换为 rune ?

hash - 用户密码的 Golang Base64 编码 SHA256 摘要

bash - 包含函数的 map 未将正确的结果返回到stdout

ios - 在 Swift 5、iOS 14 中编码可编码结构时出现 NSJSONSerialization 错误 : Invalid top-level type in JSON write

java - 日期JSON解析形式

json - 防止暴露 JSON 数据 - wp-json/contact-form-7/v1/

javascript - 如何使用 AJAX post 方法从 PHP 的特定函数中检索 JSON