【Go】JSON库(一)之结构体、map、切片转json

2021-09-16 10:41:47 浏览数 (1)

  1. 结构体转json
代码语言:javascript复制
package main

import (
	"encoding/json"
	"fmt"
)

/*{
	"name":"王二狗",
	"age":30,
	"sex":true,
	"hobby":["eat","drink","run"],
	"wife":{"name":"小狗","sex":false},
	"aunts":[{"name":1},{"name":2},{"name":3}]


}*/
type Person1 struct {
	Name string
	Age int
	Rmb float64
	Sex bool
	Hobby []string

}

func main() {

	person1 := Person1{"于谦", 50, 123.22, true, []string{"eat", "drink"}}
	marshal, err := json.Marshal(person1)
	if err != nil{
		fmt.Println("序列化失败,err=",err)
		return
	}
	fmt.Println(string(marshal))
}
  1. map转json
代码语言:javascript复制
package main

import (
	"encoding/json"
	"fmt"
)

/*{
	"name":"王二狗",
	"age":30,
	"sex":true,
	"hobby":["eat","drink","run"],
	"wife":{"name":"小狗","sex":false},
	"aunts":[{"name":1},{"name":2},{"name":3}]


}*/

func main() {
	dataMap := make(map[string]interface{})
	dataMap["name"] = "于谦"
	dataMap["age"] = 50
	dataMap["rmb"] = 2314.14
	dataMap["sex"] = true
	dataMap["hobby"] = []string{"eat","drink"}

	bytes, err1 := json.Marshal(dataMap)
	if err1 != nil{
		fmt.Println("序列化失败,err=",err)
		return
	}
	fmt.Println(string(bytes))

}
  1. 切片转json
代码语言:javascript复制
package main

import (
	"encoding/json"
	"fmt"
)

/*{
	"name":"王二狗",
	"age":30,
	"sex":true,
	"hobby":["eat","drink","run"],
	"wife":{"name":"小狗","sex":false},
	"aunts":[{"name":1},{"name":2},{"name":3}]


}*/
type Person1 struct {
	Name string
	Age int
	Rmb float64
	Sex bool
	Hobby []string

}

func main() {

	person1 := Person1{"于谦", 50, 123.22, true, []string{"eat", "drink"}}
	marshal, err := json.Marshal(person1)
	if err != nil{
		fmt.Println("序列化失败,err=",err)
		return
	}
	fmt.Println(string(marshal))

	dataMap := make(map[string]interface{})
	dataMap["name"] = "于谦"
	dataMap["age"] = 50
	dataMap["rmb"] = 2314.14
	dataMap["sex"] = true
	dataMap["hobby"] = []string{"eat","drink"}

	bytes, err1 := json.Marshal(dataMap)
	if err1 != nil{
		fmt.Println("序列化失败,err=",err)
		return
	}
	fmt.Println(string(bytes))

	dataSlice := make([]map[string]interface{},0)
	dataMap1 := make(map[string]interface{})
	dataMap1["name"] = "王小波"
	dataMap1["age"] = 12
	dataMap1["rmb"] = 2322214.14
	dataMap1["sex"] = true
	dataMap1["hobby"] = []string{"eat","read"}

	dataMap2 := make(map[string]interface{})
	dataMap2["name"] = "王波"
	dataMap2["age"] = 19
	dataMap2["rmb"] = 2324.14
	dataMap2["sex"] = true
	dataMap2["hobby"] = []string{"run","read"}

	dataSlice = append(dataSlice, dataMap1, dataMap2)
	ipp, err2 := json.Marshal(dataSlice)
	if err2 != nil{
		fmt.Println(err)

	}
	fmt.Println(string(ipp))
}

0 人点赞