GoLang 序列化与反序列化

json和struct互相转换

package main

import (
	"encoding/json"
	"fmt"
)

type Movie struct { //定义一个结构体
	Title  string   `json:"title"`
	Year   int      `json:"year"`
	Price  int      `json:"price"`
	Actors []string `json:"actors"`
}

func main() {
	movie := Movie{"喜剧之王", 2000, 10, []string{"xingye", "zhangbozhi"}}
	jsonStr, err := json.Marshal(movie) //struct转json
	if err != nil {
		fmt.Println("json marshal error: ", err)
		return
	}

	fmt.Println("jsonStr = ", string(jsonStr))

	myMovie := Movie{}
	err = json.Unmarshal(jsonStr, &myMovie) //json转struct
	if err != nil {
		fmt.Println("json unmarshal error: ", err)
		return
	}
	fmt.Println("jsonStruct = ", myMovie)
}

打印结果:

jsonStr =  {"title":"喜剧之王","year":2000,"price":10,"actors":["xingye","zhangbozhi"]}
jsonStruct =  {喜剧之王 2000 10 [xingye zhangbozhi]}