golang中结构体标签在json中的应用

package main

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

type Movie struct {
	Title string `json:"title"`
	Year int `json:"year"`
	Price int `json:"rmb"`
	Actors []string `json:"actors"`
}

func main() {
	var movie = Movie{"长津湖", 2021, 54, []string{"吴京", "易烊千玺"}}

	// 编码的过程 结构体---》json
	jsonByte, err := json.Marshal(movie)
	if err != nil {
		fmt.Println("json Marshal error", err.Error())
	} else {
		// 将字节切片转换为字符串
		//fmt.Println(string(jsonByte))
		fmt.Printf("%s\n", jsonByte)
		fmt.Println(reflect.TypeOf(jsonByte))
	}

	// 解码的过程 json--->结构体
	var movie2 Movie
	json.Unmarshal(jsonByte, &movie2)
	fmt.Println(movie2)
	fmt.Println(reflect.TypeOf(movie2))

}

  

posted @ 2021-10-30 09:48  专职  阅读(209)  评论(0编辑  收藏  举报