go json序列化json.Marshal()

package main

import (
	"encoding/json"
	"fmt"
)

type student struct {
	Name  string
	Age   int
	Score float32
	Hobby []string
}

var (
	zhangsan, lisi student
	stuSpl         []student
	mmp            map[string]interface{}
)

func init() {
	zhangsan = student{"张三", 12, 95.5, []string{"乒乓球", "绘画"}}
	lisi = student{"李四", 13, 97, []string{"篮球", "朗诵"}}

	stuSpl = append(stuSpl, zhangsan, lisi)

	mmp = make(map[string]interface{})
	mmp["persons"]=stuSpl

}

func main() {
	//结构体的序列化
	if bytes, e := json.Marshal(zhangsan); e == nil {
		fmt.Println(string(bytes))
	} else {
		fmt.Println("转换失败错误:", e)
	}
	//切片序列化
	if bytes, e := json.Marshal(stuSpl); e == nil {
		fmt.Println(string(bytes))
	} else {
		fmt.Println("转换失败错误:", e)
	}
	//map序列化
	if bytes, e := json.Marshal(mmp); e == nil {
		fmt.Println(string(bytes))
	} else {
		fmt.Println("转换失败错误:", e)
	}

}

 

你可能感兴趣的:(Go)