(五)json包的使用

encoding/json

package main

import (
	"encoding/json"
	"fmt"
)

type Movie struct {
	Title  string   "name"
	Year   int      "year"
	Blue   bool     ""
	Actors []string "actor array"
}

func JsonTest() {
	m := new(Movie)
	m.Title = "tom and jerry"
	m.Year = 1992
	m.Blue = false
	m.Actors = []string{"tom", "jerry"}
	fmt.Println(m)

	// json.Marshal
	data, err := json.Marshal(m)
	if err != nil {
		fmt.Println(err.Error())
	}
	fmt.Println(data)
	fmt.Printf("%s\n", data)

	// json.MarshalIndent
	data, err = json.MarshalIndent(m, "", "  ")
	if err != nil {
		fmt.Println(err.Error())
	}
	fmt.Println(data)
	fmt.Printf("%s\n", data)

	// json.Unmarshal
	um := new(Movie)
	if err := json.Unmarshal(data, um); err != nil {
		fmt.Println(err.Error())
	}
	fmt.Println(um)
}

func main() {
	JsonTest()
}

posted @ 2018-12-28 20:50  yvhqbat  阅读(160)  评论(0编辑  收藏  举报