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
", data)
// json.MarshalIndent
data, err = json.MarshalIndent(m, "", " ")
if err != nil {
fmt.Println(err.Error())
}
fmt.Println(data)
fmt.Printf("%s
", data)
// json.Unmarshal
um := new(Movie)
if err := json.Unmarshal(data, um); err != nil {
fmt.Println(err.Error())
}
fmt.Println(um)
}
func main() {
JsonTest()
}