package main
import("encoding/json""fmt""os""time")type info struct{
Name string`json:"name"`
Age int`json:"age"`
Extra interface{}`json:"extra"`}// json.Unmarshal 将字符串解析为对应的结构体functestUnmarshal(){
str :=`{"name": "code-machine", "age": 18,
"extra": {"phoneNumber": "8008208820", "hobby": ["LOL", "CF", "CS", "CSGO"]}}`var s info
if err := json.Unmarshal([]byte(str),&s); err !=nil{panic(err)}
fmt.Println(s.Name)
fmt.Println(s.Age)
fmt.Println(s.Extra)}// json.Marshal 将结构体解析为[]bytefunctestMarshal(){type extra struct{
PhoneNumber string`json:"phoneNumber"`
Hobby []string`json:"hobby"`}
e := extra{
PhoneNumber:"8008208820",
Hobby:[]string{"LOL","CF","CS","CSGO"},}
s :=&info{
Name:"code-machine",
Age:18,
Extra: e,}
ret, err := json.Marshal(s)if err !=nil{panic(err)}
fmt.Println(string(ret))}/*
Use json.Decoder if your data is coming from an io.Reader stream, or you need to decode multiple values from a stream of data.
For the case of reading from an HTTP request, I'd pick json.Decoder since you're obviously reading from a stream.
Use json.Unmarshal if you already have the JSON data in memory.
*/// 从io.Reader中读取内容并解析为对应的结构体functestDecode(){type moreInfo struct{
Address string`json:"address"`
Job string`json:"job"`}// 文件内容:// {"name": "code-machine", "age": 18, "extra": {"phoneNumber": "8008208820", "hobby": ["LOL", "CF", "CS", "CSGO"]}}{"address": "ShangHai", "job": "monkey"}// 文件中包含两个json,一个格式为info, 一个格式为moreInfo
f, err := os.Open("./test-file")if err !=nil{panic(err)}defer f.Close()// s一定要定义为结构体指针
s :=&info{}
d := json.NewDecoder(f)// 一定要先解析第一个格式为info的字符串,否则得不到想要的结果if err := d.Decode(s); err !=nil{panic(err)}
fmt.Println(s)// 将剩下的内容(格式为moreInfo的字符串)读取到buf中,进行后续处理
remainder := d.Buffered()
more :=&moreInfo{}
b :=make([]byte,100)// 从buf中取出剩余内容
n, err := remainder.Read(b)if err !=nil{panic(err)}
fmt.Println(string(b))// 解析为对应的格式if err := json.Unmarshal(b[:n], more); err !=nil{panic(err)}
fmt.Println(more)}// 将结构体解析为字符串后写入io.WriterfunctestEncode(){type encode struct{
Time int64`json:"time"`
Context string`json:"context"`}
f, err := os.OpenFile("./test-file", os.O_APPEND, os.ModeAppend)if err !=nil{panic(err)}
e := json.NewEncoder(f)
s :=&encode{
Time: time.Now().Unix(),
Context:"test json",}if err := e.Encode(s); err !=nil{panic(err)}}funcmain(){//testUnmarshal()//testMarshal()//testDecode()testEncode()}