go实现Json序列化的几种方式
type Person struct {
Name string `json:"nickName"`
Age int `json:"age"`
Birthday string
Sal float64
Skill string
}
func testStruct() {
person :=Person{
Name: "老zhou",
Age: 43,
Birthday: "1982-11-11",
Sal: 8000.0,
Skill: "爱狗叫",
}
data, err := json.Marshal(&person)
if err != nil {
fmt.Printf("序列号错误 err=%v\n", err)
}
fmt.Printf("person 序列化后=%v\n", string(data))
}
func testMap() {
var a map[string]interface{}
a = make(map[string]interface{})
a["name"] = "老王"
a["age"] = 30
a["address"] = "隔壁"
data, err := json.Marshal(a)
if err != nil {
fmt.Printf("序列化错误 err=%v\n", err)
}
fmt.Printf("a map 序列化后=%v\n", string(data))
}
func testSlice() {
var slice []map[string]interface{}
var m1 map[string]interface{}
m1 = make(map[string]interface{})
m1["name"] = "赵本山"
m1["age"] = "64"
m1["address"] = "铁岭"
slice = append(slice, m1)
var m2 map[string]interface{}
m2 = make(map[string]interface{})
m2["name"] = "许嵩"
m2["age"] = "18"
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))
}
func testFloat64() {
var num1 float64 = 2345.67
data, err := json.Marshal(num1)
if err != nil {
fmt.Printf("序列化错误 err=%v\n", err)
}
fmt.Printf("num1 序列化后=%v\n", string(data))
}