我试图从服务器返回一些JSON数据,但在使用以下代码时遇到了这个错误
cannot use buffer (type *bytes.Buffer) as type []byte in argument to w.Write
通过一点谷歌搜索,我找到了这个SO答案,但无法使其正常工作(请参见带有错误消息的第二个代码示例)
第一个代码示例
buffer := new(bytes.Buffer)
for _, jsonRawMessage := range sliceOfJsonRawMessages{
if err := json.Compact(buffer, jsonRawMessage); err != nil{
fmt.Println("error")
}
}
fmt.Println("json returned", buffer)//this is json
w.Header().Set("Content-Type", contentTypeJSON)
w.Write(buffer)//error: cannot use buffer (type *bytes.Buffer) as type []byte in argument to w.Write
第二个代码示例中存在错误
cannot use foo (type *bufio.Writer) as type *bytes.Buffer in argument to json.Compact
cannot use foo (type *bufio.Writer) as type []byte in argument to w.Write
var b bytes.Buffer
foo := bufio.NewWriter(&b)
for _, d := range t.J{
if err := json.Compact(foo, d); err != nil{
fmt.Println("error")
}
}
w.Header().Set("Content-Type", contentTypeJSON)
w.Write(foo)
fmt.Println("json returned", buffer.Bytes())
,如果我将buffer.Bytes()传递给w.Write,它也会返回一串字节流。我需要返回JSON。请注意,我无法测试此功能,因为我的浏览器存在其他问题。 - Leahcimbuffer.String()
。buffer.Bytes()
返回 JSON 文本的 UTF-8 编码字节。 - icza