标签:float pre rsh ons type append ring func err
package main import ( "fmt" "encoding/json" ) //定义一个结构体 type Monster struct { Name string `json:"monster_name"` //反射机制 Age int `json:"monster_age"` Birthday string Sal float64 Skill string } func testStruct() { //演示 monster := Monster{ Name :"牛魔王", Age : 500 , Birthday : "2011-11-11", Sal : 8000.0, Skill : "牛魔拳", } fmt.Println(monster.Name) //牛魔王 //将monster序列化 data, err := json.Marshal(&monster) //元帅;马萨克;马歇尔;列集;调度 if err != nil { fmt.Printf("序列号错误 err=%v\n", err) } //输出序列化后的结果 fmt.Printf("monster序列化后=%v\n", string(data)) //monster序列化后={"monster_name":"牛魔王","monster_age":500,"Birthday":"2011-11-11","Sal":8000,"Skill":"牛魔拳"} } func main() { testStruct() }
package main import ( "fmt" "encoding/json" ) //将map进行序列化 func testMap() { //定义一个map var a map[string]interface{} //可以把任何类型的变量给空接口 //使用map,需要make a = make(map[string]interface{}) a["name"] = "红孩儿" a["age"] = 30 a["address"] = "洪崖洞" //将a这个map进行序列化 //将monster 序列化 data, err := json.Marshal(a) if err != nil { fmt.Printf("序列化错误 err=%v\n", err) } //输出序列化后的结果 fmt.Printf("a map 序列化后=%v\n", string(data)) //a map 序列化后={"address":"洪崖洞","age":30,"name":"红孩儿"} } func main() { testMap() }
package main import ( "fmt" "encoding/json" ) //演示对切片进行序列化, 我们这个切片 []map[string]interface{} func testSlice() { var slice []map[string]interface{} //可以把任何类型的变量给空接口 var m1 map[string]interface{} //使用map前,需要先make m1 = make(map[string]interface{}) m1["name"] = "jack" m1["age"] = "7" m1["address"] = "北京" slice = append(slice, m1) var m2 map[string]interface{} //使用map前,需要先make m2 = make(map[string]interface{}) m2["name"] = "tom" m2["age"] = "20" m2["address"] = [2]string{"墨西哥","夏威夷"} slice = append(slice, m2) //将切片进行序列化操作 data, err := json.Marshal(slice) if err != nil { fmt.Printf("序列化错误 err=%v\n", err) } //输出序列化后的结果 fmt.Printf("slice 序列化后=%v\n", string(data)) //slice 序列化后=[{"address":"北京","age":"7","name":"jack"},{"address":["墨西哥","夏威夷"],"age":"20","name":"tom"}] } func main() { testSlice()//演示对切片的序列化 }
package main import ( "fmt" "encoding/json" ) //对基本数据类型序列化,对基本数据类型进行序列化意义不大(只是转成字符串而已) func testFloat64() { var num1 float64 = 2345.67 //对num1进行序列化 data, err := json.Marshal(num1) if err != nil { fmt.Printf("序列化错误 err=%v\n", err) } //输出序列化后的结果 fmt.Printf("num1 序列化后=%v\n", string(data)) //num1 序列化后=2345.67 } func main() { testFloat64()//演示对基本数据类型的序列化 }
标签:float pre rsh ons type append ring func err
原文地址:https://www.cnblogs.com/yzg-14/p/12233725.html