使用golang appengine解码JSON URL GET请求时遇到问题。
我是Golang的新手,这可能只是一个简单的修复。
无法将bytes.Buffer转换为struct。我做得对吗?
或者我可以只查询我想要的字段的字符串,但我认为这样做会错。
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
答案 0 :(得分:0)
我假设你的json作为一个对象的最外层元素,所以它看起来可能像{"key": [{"type": "foo"}]}
。
但是你试图解组成一个数组,所以它应该看起来像[{"type": "foo"}]
。
确保你必须张贴你的json的例子。
答案 1 :(得分:0)
感谢您的帮助,按照这个答案的建议(下面的链接),我能够找出正确的json结构,并且我在结构声明中缺少一层。
Golang issue with accessing Nested JSON Array after Unmarshalling
// fixed
type Result struct {
Features []struct {
Type string `json:"type"`
.
.
.