golang encoding/json

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
 1 package main 2  3 import ( 4     "bytes" 5     "encoding/json" 6     "fmt" 7 ) 8  9 type ColorGroup struct {10     ID     int11     Name   string12     Colors []string13 }14 15 func main() {16 17     //---------------Marshal18     group := ColorGroup{19         ID:     1,20         Name:   "Reds",21         Colors: []string{"Crimson", "Red", "Ruby", "Maroon"},22     }23     b, err := json.Marshal(group)24     if err != nil {25         fmt.Println("error:", err)26     }27     //os.Stdout.Write(b)28     fmt.Println(string(b[:]))29 30     //---------------Unmarshal31     var jsonBlob = []byte(`[32             {"ID":1,"Name":"Reds1","Colors":["Crimson","Red1","Ruby1","Maroon1"]},33             {"ID":2,"Name":"Reds2","Colors":["Crimson","Red2","Ruby2","Maroon2"]},34             {"ID":3,"Name":"Reds3","Colors":["Crimson","Red3","Ruby3","Maroon3"]}35         ]`)36 37     var animals []ColorGroup38     error := json.Unmarshal(jsonBlob, &animals)39     if error != nil {40         fmt.Println("error:", error)41     }42 43     //fmt.Printf("%+v", animals)44     //fmt.Println(animals)45     for i, x := range animals {46         fmt.Println(i, x)47 48     }49     //---------------Indent50     dst := new(bytes.Buffer)51     json.Indent(dst, jsonBlob, "##", "**")52     fmt.Println(dst)53 }

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.