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: 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"}}。


如何解决这个问题?


潇湘沐
浏览 92回答 1
1回答

慕运维8079593

&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: ...}}。您可以在此处阅读有关复合文字 的更多信息。
打开App,查看更多内容
随时随地看视频慕课网APP