package main
//json 与struct转化
import (
"encoding/json"
"fmt"
)
// 结构体首字母要大写打印出来后给的别名
type People struct {
Name string `json:"name_title"`
Age int `json:"age_size"`
}
//struct 转json
func StructToJsonDemo() {
p := People{
Name: "alpha",
Age: 18,
}
jsonBytes, err := json.Marshal(p) //结构体转json序列化
if err != nil {
fmt.Println(err)
}
fmt.Println(string(jsonBytes))
}
//json转化为结构体
func JsonToStructDemo(){
jsonStr := `
{
"name_title": "alpha"
"age_size":12
}
`
var people People
json.Unmarshal([]byte(jsonStr), &people)
fmt.Println(people.Age,people.Name)
}
// json转map
func JsonToMapDemo(){
jsonStr := `
{
"name": "alpha",
"age": 18
}
`
var mapResult map[string]interface{
}//传地址才会修改该map
err := json.Unmarshal([]byte(jsonStr), &mapResult)
if err != nil {
fmt.Println("JsonToMapDemo err: ", err)
}
fmt.Println(mapResult)
}
//map转json
func MapToJsonDemo(){
mapInstances := []map[string]interface{
}{
}
instance_1 := map[string]interface{
}{
"name": "John", "age": 10}
instance_2 := map[string]interface{
}{
"name": "Alex", "age": 12}
mapInstances = append(mapInstances, instance_1, instance_2)
jsonStr, err := json.Marshal(mapInstances)
if err != nil {
fmt.Println("MapToJsonDemo err: ", err)
}
fmt.Println(string(jsonStr))
}
func main() {
StructToJsonDemo()
StructToJsonDemo()
JsonToMapDemo()
MapToJsonDemo()
}
go - json -struct
猜你喜欢
转载自blog.csdn.net/alpha_love/article/details/115422538
今日推荐
周排行