我有以下代碼,我只想測驗我是否正確編組我的 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: syntax error: unexpected &, expecting type.
Line no: 28因為我的代碼是MyJSON := &TestSpec{Files: []&TestFileList{File: &TestFile{Download_Seconds: 600, Name: "filename1"}, File: &TestFile{Download_Seconds: 1200, Name: "filename2"}}}
Go marshaling 相當新。我想我做錯了[]&TestFileList{File: &TestFile{Download_Seconds: 600, Name: "filename1"}, File: &TestFile{Download_Seconds: 1200, Name: "filename2"}}。
如何解決這個問題?
uj5u.com熱心網友回復:
&TestSpec{
Files: []*TestFileList{
{File: &TestFile{Download_Seconds: 600, Name: "filename1"}},
{File: &TestFile{Download_Seconds: 1200, Name: "filename2"}},
},
}
https://go.dev/play/p/I30Mm0CxrUT
請注意,除了 Zombo 在評論中指出的錯誤之外,您還省略了分隔切片中各個元素的花括號,即您有{File: ..., File: ...},但應該是{{File: ...}, {File: ...}}。
您可以在此處閱讀有關復合文字 的更多資訊。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/447728.html
