文章来源于网络收集而来,版权归原创者所有,如有侵权请及时联系!
序列化
package main
import (
"encoding/json"
"fmt"
)
type Monster struct {
Name string `json:"name"`
Age int `json:"age"`
Birthday string `json:"birthday"`
Sal float64 `json:"sal"`
Skill string `json:"skill"`
}
/*结构体序列化*/
func NewMinsterStruct() {
monster := Monster{
Name: "孙悟空",
Age: 500,
Birthday: "2011-11-11",
Sal: 8000.0,
Skill: "如意七十二变",
}
data, err := json.Marshal(&monster)
if err != nil {
fmt.Printf("序列化错误 err:%v\n", err)
}
fmt.Printf("Map 序列化后=%v\n", string(data))
}
/*Map 序列化*/
func MapSerlizer() {
var a map[string]interface{}
a = make(map[string]interface{})
a["name"] = "牛魔王"
a["age"] = 10
a["address"] = "火云洞"
data, err := json.Marshal(a)
if err != nil {
fmt.Printf("序列化错误 err:%v\n", err)
}
fmt.Printf("monster 序列化后=%v\n", string(data))
}
/*切片序列化*/
func SliceSerlizer() {
var slice []map[string]interface{}
var m1 map[string]interface{}
m1 = make(map[string]interface{})
m1["name"] = "TGH"
m1["age"] = "19"
m1["address"] = "北京"
slice = append(slice, m1)
var m2 map[string]interface{}
m2 = make(map[string]interface{})
m2["name"] = "FCC"
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("切片序列化后=%v\n", string(data))
}
/*基本数据类型序列化*/
func FloatSerlize() {
var num1 float64 = 245.56
data, err := json.Marshal(num1)
if err != nil {
fmt.Printf("序列化错误 err:%v\n", err)
}
fmt.Printf("基本数据类型序列化后=%v\n", string(data))
}
func main() {
NewMinsterStruct()
MapSerlizer()
SliceSerlizer()
FloatSerlize()
}
Map 序列化后={"name":"孙悟空","age":500,"birthday":"2011-11-11","sal":8000,"skill":"如意七十二变"}
monster 序列化后={"address":"火云洞","age":10,"name":"牛魔王"}
切片序列化后=[{"address":"北京","age":"19","name":"TGH"},{"address":["华府","影视帝国"],"age":"18","name":"FCC"}]
基本数据类型序列化后=245.56
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论