1、通过结构体生成json
示例:
package main import ( "encoding/json" "fmt" ) //成员变量名首字母必须大写 type IT struct { Company string Subjects []string IsOk bool Price float64 } func main() { //定义一个结构体变量,同时初始化 s := IT{"itcast", []string{"Go", "C++", "Python", "Test"}, true, 666.666} //编码,根据内容生成json文本 buf, err := json.Marshal(s) if err != nil { fmt.Println("err = ", err) return } fmt.Println("buf = ", string(buf)) }
执行结果:
buf = {"Company":"itcast","Subjects":["Go","C++","Python","Test"],"IsOk":true,"Price":666.666}
2、根据结构体生成json
package main import ( "encoding/json" "fmt" ) //成员变量名首字母必须大写 type IT struct { Company string Subjects []string IsOk bool Price float64 } func main() { //定义一个结构体变量,同时初始化 s := IT{"itcast", []string{"Go", "C++", "Python", "Test"}, true, 666.666} //编码,根据内容生成json文本 buf, err := json.MarshalIndent(s, "", " ") //格式化编码 if err != nil { fmt.Println("err = ", err) return } fmt.Println("buf = ", string(buf)) }
执行结果:
buf = { "Company": "itcast", "Subjects": [ "Go", "C++", "Python", "Test" ], "IsOk": true, "Price": 666.666 }
3、struct_tag的使用 (通过二次编码,可以把大写变成小写,还可以以字符串方式输出)
示例:
package main import ( "encoding/json" "fmt" ) //成员变量名首字母必须大写 type IT struct { //Company string `json:"-"` //此字段不会输出到屏幕 //下面的写法都是二次编码,可以把大写变成小写 Company string `json:"company"` Subjects []string `json:"subjects"` IsOk bool `json:"isok"` //转成字符串再输出编码 //IsOk bool `json:"string"` Price float64 `json:"price"` } func main() { //定义一个结构体变量,同时初始化 s := IT{"itcast", []string{"Go", "C++", "Python", "Test"}, true, 666.666} //编码,根据内容生成json文本 buf, err := json.MarshalIndent(s, "", " ") //格式化编码 if err != nil { fmt.Println("err = ", err) return } fmt.Println("buf = ", string(buf)) }
执行结果:
buf = { "company": "itcast", "subjects": [ "Go", "C++", "Python", "Test" ], "isok": true, "price": 666.666 }