将*bytes.Buffer转换为json并在应用程序引擎中进行反序列化

3

使用golang appengine时,解码JSON URL GET请求遇到了问题。

我是golang的新手,这可能只是一个简单的修复。

无法将bytes.Buffer转换为结构体。我的做法正确吗?

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

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.Unmarshal返回的错误是什么?此外,您可以将代码从创建bytes.Buffer的行替换为调用json.Unmarshal的行:var MyResult []Result; err := json.NewDecoder(resp.Body).Decode(&MyResult) - Charlie Tumahai
解码时出现了什么错误?您能打印string(buf.Bytes())Unmarshal上的错误吗? - Sarath Sadasivan Pillai
json.Unmarshal 返回的错误是什么?json:无法将对象解组为类型为 []main.Result 的 Go 值。 - Chief2017
错误表明您正在将JSON对象解组为切片。请更新问题并提供错误和JSON文本,以便我们可以为您提供进一步的帮助。您可以通过打印buf.String()来获取JSON文本。 - Charlie Tumahai
2个回答

0

我假设你的JSON最外层元素是一个对象,所以它看起来可能像这样:{"key": [{"type": "foo"}]}

但你尝试将其解组成一个数组,所以它应该像这样:[{"type": "foo"}]

为了确保,你需要发布一个JSON示例。


0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接