2019-01-19 Golang学习笔记-JSON操作

2019-01-19 Golang学习笔记-JSON操作

1.序列化map类型

package main

import (
	"encoding/json"
	"fmt"
	"strconv"
)

// 注意这里的Person的各个字段一定要大写!!!
type Person struct {
	Name string
	Age int
	Location string
	Remark string
}
func main() {
	/*
		序列化map类型
	*/
	var testMap map[string]string
	testMap = make(map[string]string, 5)

	testMap["01"] = "小张"
	testMap["02"] = "小李"
	testMap["03"] = "小王"
	testMap["04"] = "小范"
	testMap["05"] = "小吴"

	byteArr, err := json.Marshal(testMap)
	if err != nil {
		fmt.Printf("error: %v\n", err)
	}
	fmt.Println(string(byteArr))

	var tsetMap2 map[int]*Person
	tsetMap2 = make(map[int]*Person, 5)

	for a :=0; a < 5; a++ {
		person := Person{}
		person.Name = "小张" + strconv.Itoa(a)
		person.Age = 18 + a
		person.Location = "陕西西安" + strconv.Itoa(a)
		person.Remark = "超级无敌" + strconv.Itoa(a)
		tsetMap2[a] = &person
	}

	byteArr2, err := json.Marshal(tsetMap2)
	if err != nil {
		fmt.Printf("error: %v\n", err)
	}
	fmt.Println(string(byteArr2))
}

2.序列化切片类型

	/*
		序列化切片
	*/
	// 创建一个Person类型切片
	var personArr []Person
	personArr = make([]Person, 5)

	for a := 0; a < 5; a++ {
		persons := Person{}
		persons.Name = "xiaohua" + strconv.Itoa(a)
		persons.Age = 18 + a
		persons.Location = "陕西西安" + strconv.Itoa(a)
		persons.Remark = "小可爱呀 嘤嘤嘤" + strconv.Itoa(a)
		personArr[a] = persons
	}
	byteArr5, err := json.Marshal(personArr)
	fmt.Println(string(byteArr5))

3.反序列化的操作

	// 反序列化
	var personSlice []Person
	 errss := json.Unmarshal(byteArr5, &personSlice)  // 注意这里是 &personSlice
	 if err != nil{
	 	fmt.Printf("error: %v", errss)
	 }
	 fmt.Println(personSlice)

你可能感兴趣的:(Go)