Go 中的指针数组 JSON 编组

Array of a pointer in Go JSON marshalling

我有以下代码,我只想测试我是否正确编组 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 封送处理还比较陌生。我想我做错了 []&TestFileList{File: &TestFile{Download_Seconds: 600, Name: "filename1"}, File: &TestFile{Download_Seconds: 1200, Name: "filename2"}}.

如何解决这个问题?

&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: ...}}.

您可以阅读更多关于复合文字 here