package main
import (
"encoding/json"
"fmt"
)
//结构体
type Monster struct {
Name string
Age int
Birthday string
Sal float64
Skill string
}
//结构体 增加tag标签
type Monster2 struct {
Name string `json:"monster"`//反射机制
Age int `json:"age"`
Birthday string `json:"birthday"`
Sal float64 `json:"sal"`
Skill string `json:"skill"`
}
//结构体序列化
func testStruct(){
monster:=Monster{
Name: "牛魔王",
Age: 500,
Birthday: "2011-11-11",
Sal: 18222,
Skill: "牛魔圈",
}
//序列化
data,err:=json.Marshal(&monster)
if err!=nil{
fmt.Printf("序列化错误 err=%v
",err)
}
fmt.Printf("monster 序列化后=%v
",string(data))
}
//结构体序列化 增加tag,字段自定义
func testStruct2(){
monster:=Monster2{
Name: "牛魔王",
Age: 500,
Birthday: "2011-11-11",
Sal: 18222,
Skill: "牛魔圈",
}
//序列化
data,err:=json.Marshal(&monster)
if err!=nil{
fmt.Printf("序列化错误 err=%v
",err)
}
fmt.Printf("monster 序列化后=%v
",string(data))
}
//map序列化
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
",err)
}
fmt.Printf("a map序列化后=%v
",string(data))
}
//切片序列化
func testSlice(){
var slice []map[string]interface{}
var m1 map[string]interface{}
m1=make(map[string]interface{})
m1["name"]="jack"
m1["age"]="7"
m1["address"]="北京"
slice=append(slice,m1)
var m2 map[string]interface{}
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
",err)
}
fmt.Printf("slice 序列化后=%v
",string(data))
}
//对基本数据类型序列化意义不大
func testFloat64(){
var num1 float64 =123456.45
data,err:=json.Marshal(num1)
if err!=nil{
fmt.Printf("序列化错误 err=%v
",err)
}
fmt.Printf("float64 序列化后=%v
",string(data))
}
func main() {
//testStruct()
//testMap()
//testSlice()
//testFloat64()
testStruct2()
}