```go
package main
import (
"fmt"
"time"
"encoding/json"
)
type HttpResponse struct {
Errorno int `json:"errorno"`
Errmsg string `json:"errmsg"`
Timestamp int64 `json:"timestamp"`
ServerStatus int `json:"serverstatus"`
Msg string `json:"msg"`
Data map[string]interface{} `json:"data"`
}
var httpresp = HttpResponse{
Errorno: 1,
// Errmsg: "error", // 编码前不对该字段赋值
Timestamp: time.Now().Unix(),
ServerStatus: 0,
Msg: "msg",
Data: map[string]interface{}{"id": 123},
}
jsonstr, err := json.Marshal(httpresp)
if err != nil {
fmt.Println("json encode err", err)
}
fmt.Println("after encoding: ", string(jsonstr))
var afterjson HttpResponse
err = json.Unmarshal(jsonstr, &afterjson)
fmt.Printf("%+v", afterjson)
output:
after encoding: {"errorno":1,"errmsg":"","timestamp":1466247295,"serverstatus":0,"msg":"msg","data":{"id":123}}
{Errorno:1 Errmsg: Timestamp:1466247295 ServerStatus:0 Msg:msg Data:map[id:123]}
说明:
1. json解码时会自动对编码字节流进行结构体里的字段进行匹配,如果匹配上了,则自动赋值给结构体变量,否则,直接舍弃。
有疑问加站长微信联系(非本文作者)