Go JSON 编组中的指针数组
我有以下代码,我只想测试我是否正确编组 JSON:
package main
import (
"encoding/json"
"fmt"
)
type TestFile struct {
Download_Seconds int `json:"download_seconds"`
Name string `json:"name"`
}
type TestFileList struct {
File *TestFile `json:"file"`
}
type TestSpec struct {
Files []*TestFileList `json:"files"`
}
func main() {
r := new(TestSpec)
b, _ := json.Marshal(r)
fmt.Println(string(b))
MyJSON := &TestSpec{Files: []&TestFileList{File: &TestFile{Download_Seconds: 600, Name: "filename1"}, File: &TestFile{Download_Seconds: 1200, Name: "filename2"}}}
b1, _ := json.Marshal(MyJSON)
fmt.Println(string(b1))
}
我收到此错误:
.\go_json_eg2.go:28:32: 语法错误:意外 & ,期待类型
。
行号:28
我的代码是 MyJSON := &TestSpec{Files: []&TestFileList{File: &TestFile{Download_Seconds: 600, Name: "filename1"},文件:&TestFile{Download_Seconds:1200,名称:“filename2”}}}
对于 Go 来说相当陌生编组。我想我做错了 []&TestFileList{File: &TestFile{Download_Seconds: 600, Name: "filename1"}, File: &TestFile{Download_Seconds: 1200, Name: "filename2"} }
。
如何解决这个问题?
I've the following code, where I want to just test whether I'm marshaling my JSON correctly or not:
package main
import (
"encoding/json"
"fmt"
)
type TestFile struct {
Download_Seconds int `json:"download_seconds"`
Name string `json:"name"`
}
type TestFileList struct {
File *TestFile `json:"file"`
}
type TestSpec struct {
Files []*TestFileList `json:"files"`
}
func main() {
r := new(TestSpec)
b, _ := json.Marshal(r)
fmt.Println(string(b))
MyJSON := &TestSpec{Files: []&TestFileList{File: &TestFile{Download_Seconds: 600, Name: "filename1"}, File: &TestFile{Download_Seconds: 1200, Name: "filename2"}}}
b1, _ := json.Marshal(MyJSON)
fmt.Println(string(b1))
}
I'm getting this error:
.\go_json_eg2.go:28:32: syntax error: unexpected &, expecting type
.
Line no: 28
for my code is MyJSON := &TestSpec{Files: []&TestFileList{File: &TestFile{Download_Seconds: 600, Name: "filename1"}, File: &TestFile{Download_Seconds: 1200, Name: "filename2"}}}
Fairly new to Go marshaling. I figured I'm doing this wrong []&TestFileList{File: &TestFile{Download_Seconds: 600, Name: "filename1"}, File: &TestFile{Download_Seconds: 1200, Name: "filename2"}}
.
How to fix this ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
https://go.dev/play/p/I30Mm0CxrUT
注意,除了指出的错误之外by Zombo 在注释中,您还省略了分隔切片中各个元素的花括号,即您有
{File: ..., File: ...}
,但它应该是{{文件:...},{文件:...}}
。您可以在此处了解有关复合文字的更多信息。
https://go.dev/play/p/I30Mm0CxrUT
Notice that besides the error pointed out by Zombo in the comments, you also left out the curly braces that delimit the individual elements in the slice, i.e. you have
{File: ..., File: ...}
, but it should be{{File: ...}, {File: ...}}
.You can read more about Composite Literals here.