GO语言的JSON01---序列化

package main

import (
	"encoding/json"
	"fmt"
)

/*
定义待序列化结构体
属性一定要可见,否则json包无法访问
*/
type Person struct {
	Name string
	Age int
	Rmb float64
	Gender bool
	Hobbies []string
}

func NewPerson(name string,age int,rmb float64,gender bool,hobbies []string) *Person {
	person :=new(Person)
	person.Name = name
	person.Age = age
	person.Rmb = rmb
	person.Gender = gender
	person.Hobbies = hobbies
	return person
}

/*
init函数会在main函数之前被系统调用
init函数用于main之前的初始化工作
*/
var person *Person
func init() {
	fmt.Println("init")
	person = NewPerson("张全蛋", 20, 0.5, true, []string{"抽烟", "喝酒", "烫头"})
	fmt.Println(person)
}

/*序列化结构体*/
func main041() {
	fmt.Println("main")
	bytes, err := json.Marshal(*person)
	if err != nil{
		fmt.Println("序列化失败err=",err)
		return
	}
	fmt.Println(string(bytes))
}

/*序列化Map*/
func main042() {
	dataMap := make(map[string]interface{})
	dataMap["Name"] = "张全蛋"
	dataMap["Age"] = "20"
	dataMap["rmb"] = "0.5"
	dataMap["gender"] = true
	dataMap["hobbies"] = []string{"抽烟", "喝酒", "烫头"}

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

/*序列化切片(内置Map)*/
func main043() {
	dataMap := make(map[string]interface{})
	dataMap["Name"] = "张全蛋"
	dataMap["Age"] = "20"
	dataMap["rmb"] = "0.5"
	dataMap["gender"] = true
	dataMap["hobbies"] = []string{"抽烟", "喝酒", "烫头"}

	dataMap2 := make(map[string]interface{})
	dataMap2["Name"] = "张lia蛋"
	dataMap2["Age"] = "20"
	dataMap2["rmb"] = "0.5"
	dataMap2["gender"] = true
	dataMap2["hobbies"] = []string{"抽烟", "喝酒", "烫头"}

	dataSlice := make([]map[string]interface{}, 0)
	dataSlice = append(dataSlice, dataMap,dataMap2)

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

/*序列化切片(内置结构体对象)*/
func main() {
	person1 := *NewPerson("张全蛋", 20, 0.5, true, []string{"抽烟", "喝酒", "烫头"})
	person2 := *NewPerson("张俩蛋", 10, 0.5, true, []string{"抽烟", "喝酒", "烫头"})

	dataSlice := make([]Person, 0)
	dataSlice = append(dataSlice, person1, person2)

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

  

posted @ 2019-12-02 22:11  Ethan_Cheng  阅读(170)  评论(0编辑  收藏  举报