转换*字节.在应用引擎中缓冲到 json 和取消封送


在使用

golang应用程序引擎解码JSON URL GET请求时遇到问题。

我是 golang 的新手,这可能是一个简单的解决方法。

无法转换字节。缓冲区到结构。我做得对吗?

或者,我可以只查询我想要的字段的字符串,但我认为这样做是错误的。

import {
"etc..."
}
.
.
// construct req.URL.String()
.
.
type Result struct {
    Type string `json:"type"`
}

func home(w http.ResponseWriter, r *http.Request) {
.
.
.
ctx := appengine.NewContext(r)
client := urlfetch.Client(ctx)
resp, err := client.Get(req.URL.String())
buf := new(bytes.Buffer)
buf.ReadFrom(resp.Body)
fmt.Fprintln(w, buf) // successfully prints the buffer to w and confirms successful JSON request from remote server
var MyResult []Result
json.Unmarshal(buf.Bytes(), &MyResult)
for l := range MyResult {
    fmt.Fprintln(w, MyResult[l].Type)
}
// Result: Empty...
// if I hard code the expected JSON string to a []byte array and Unmarshal I get a valid result from MyResult struct

我假设您的 json 将对象的最外部元素作为对象,因此它看起来像 {"key": [{"type": "foo"}]} .

但是您尝试解组到一个数组中,因此它看起来像[{"type": "foo"}]

为了确保您必须发布一个 json 的示例。

感谢您的帮助,按照此答案的建议(下面的链接),我能够找出正确的 json 结构,并且结构声明中缺少一个层。

解组后访问嵌套 JSON 数组的 Golang 问题

// fixed
type Result struct {
    Features []struct {
        Type string `json:"type"`
        .
        .
        .

最新更新