Go struct 2 JSON

Source: Internet
Author: User
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/

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.