package main
import (
"encoding/json"
"fmt"
)
type userInfo struct {
Name string `json:"name,omitempty"` // 加上json 这个 会将 Name 转换成 name
Age int `json:"age,omitempty"`
}
func main() {
//structAndJson()
mapAndJson()
}
// 结构体转json
func structAndJson() {
user1 := userInfo{
Name: "张三",
Age: 20,
}
fmt.Println(user1) // {张三 20}
data, err := json.Marshal(&user1)
if err != nil {
fmt.Println(err)
}
fmt.Println(string(data)) // {"Name":"张三","Age":20}
user2 := userInfo{}
err1 := json.Unmarshal([]byte(data), &user2)
if err != nil {
fmt.Println(err1)
}
fmt.Println(user2) // {张三 20}
}
2. 切片结构体转json
// 切片map 转json
func mapAndJson() {
maps := []map[string]string{}
m1 := make(map[string]string)
m1["name"] = "六四"
m1["age"] = "30"
maps = append(maps, m1)
m2 := make(map[string]string)
m2["sex"] = "男人"
m2["age"] = "23"
maps = append(maps, m2)
data, err := json.Marshal(&maps)
if err != nil {
fmt.Println(err)
}
fmt.Println(string(data)) // [{"age":"30","name":"六四"},{"age":"23","sex":"男人"}]
mapjson := []map[string]string{}
err1 := json.Unmarshal([]byte(data), &mapjson)
if err1 != nil {
fmt.Println(err1)
}
fmt.Println(mapjson) // [map[age:30 name:六四] map[age:23 sex:男人]]
}
发表评论