This is a creation in Article, where the information may have evolved or changed.
// 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())}}
Output:
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类型的值将会被转化为 Base64 编码后的字符串, slice类型的零值会被转化为 null。 结构体会转化为JSON对象,并且只有结构体里边以大写字母开头的可被导出的字段才会被转化输出,而这些可导出的字段会作为JSON对象的字符串索引。 转化一个map类型的数据结构时,该数据的类型必须是 map[string]T(T可以是encoding/json 包支持的任意数据类型)
Field output
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/