Go struct 2 json

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
// struct2json project main.gopackage mainimport ("encoding/json""fmt")type Book struct {Title       stringAuthors     []stringPublisher   stringIsPublished boolPrice       float32}func main() {gobook := Book{Title:       "Go 語言編程",Authors:     []string{"XuShiwei", "HughLv", "XuDaoli"},Publisher:   "ituring.com.cn",IsPublished: true,Price:       9.99,}b, err := json.Marshal(gobook)if err == nil {fmt.Println("json = ", string(b))} else {fmt.Println("json.Marshal err : ", err.Error())}}

輸出:

json =  {"Title":"Go 語言編程","Authors":["XuShiwei","HughLv","XuDaoli"],"Publisher":"ituring.com.cn","IsPublished":true,"Price":9.99}
在Go中, JSON轉化前後的資料類型映射如下。 布爾值轉化為JSON後還是布爾類型。 浮點數和整型會被轉化為JSON裡邊的常規數字。 字串將以UTF-8編碼轉化輸出為Unicode字元集的字串,特殊字元比如<將會被轉義為\u003c。 數組和切片會轉化為JSON裡邊的數組,但[]byte類型的值將會被轉化為 Base 64 編碼後的字串, slice類型的零值會被轉化為 null。 結構體會轉化為JSON對象,並且只有結構體裡邊以大寫字母開頭的可被匯出的欄位才會被轉化輸出,而這些可匯出的欄位會作為JSON對象的字串索引。 轉化一個map類型的資料結構時,該資料的類型必須是 map[string]T(T可以是encoding/json 包支援的任意資料類型)

// 欄位輸出

type Book struct {Title       stringAuthors     []stringPublisher   stringIsPublished boolPrice       float32}func (b *Book) String() string {return fmt.Sprintf("Title = %s, \nAuthors = %v, \nPublisher = %s, \nIsPublished=%t, \nPrice = %g", b.Title, b.Authors, b.Publisher, b.IsPublished,b.Price)}/*  fmt.Println(gobook.String())*/

https://golang.org/pkg/fmt/

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.