package main
import (
"encoding/json"
"fmt"
)
type Human struct {
Name string
Age int
From string
}
// Tag 形式
// type Human struct {
// Name string `json:"n"`
// Age int `json:"a"`
// From string `json:"f"`
// }
/*
MacintoshdeMacBook-Pro-139:json elasticnotes$ go run json.go
struct序列化: {"n":"弹力笔记-struct","a":3,"f":"WEB"}
map序列化: {"Age":3,"From":"WEB","Name":"弹力笔记-map"}
*/
func SerializeStruct() {
info := new(Human)
info.Name = "弹力笔记-struct"
info.Age = 3
info.From = "WEB"
// 序列化成 json字节数组
data, err := json.Marshal(info)
if err != nil {
fmt.Println("Marshal err", err)
return
}
fmt.Println("struct序列化:", string(data))
}
func SerializeMap() {
info := make(map[string]interface{})
info["Name"] = "弹力笔记-map"
info["Age"] = 3
info["From"] = "WEB"
// 序列化成 json字节数组
data, err := json.Marshal(info)
if err != nil {
fmt.Println("Marshal err:", err)
return
}
fmt.Println("map序列化:", string(data))
}
func main() {
SerializeStruct()
SerializeMap()
}
// 输出
MacintoshdeMacBook-Pro-139:json elasticnotes$ go run json.go
struct序列化: {"Name":"弹力笔记-struct","Age":3,"From":"WEB"}
map序列化: {"Age":3,"From":"WEB","Name":"弹力笔记-map"}