Go语言map与json串相互转化
1、Go语言map与json串相互转化
- map转为Json串(本质是string),先把map转为byte数组,再把byte数组转为Json串
- Json串(本质是string)转为map,先把Json串转为byte数组,再把byte数组转为map
package main
import (
"encoding/json"
"fmt"
)
func main() {
//map转为json串(本质是string)
//先把map转为byte数组
//再把byte数组转为json串
DataMap := map[string]int{"a": 1, "b": 2, "c": 3}
marshal, err := json.Marshal(DataMap)
if err != nil {
fmt.Printf("Map转化为byte数组失败,异常:%s\n", err)
return
}
fmt.Printf("Map转化为byte数组成功:%v\n", marshal)
fmt.Printf("byte数组转化为Json串成功:%s\n", string(marshal))
//json串(本质是string)转为map
//先把json串转为byte数组
//再把byte数组转为map
dataStr := `{"a":1,"b":2,"c":3}`
var dataMap map[string]int
err = json.Unmarshal([]byte(dataStr), &dataMap)
if err != nil {
fmt.Printf("Json串转化为Map失败,异常:%s\n", err)
return
}
fmt.Printf("Json串(本质是string)转化为Map成功:%v", dataMap)
}
2、结构体或者结构体数组转为Json串
package main
import (
"encoding/json"
"fmt"
)
type S struct {
Name string `json:"name,omitempty"`
Age int `json:"age,omitempty"`
Sex string `json:"sex,omitempty"`
}
func main() {
s := S{
Name: "小红",
Age: 18,
Sex: "女",
}
marshal, err := json.Marshal(s)
if err != nil {
return
}
fmt.Println(string(marshal))
sList := []S{{
Name: "小红",
Age: 18,
Sex: "女",
}, {
Name: "小李",
Age: 20,
Sex: "男",
}, {
Name: "夏龙",
Age: 18,
Sex: "女",
}}
marshal, err = json.Marshal(sList)
if err != nil {
return
}
fmt.Println(string(marshal))
}