go中json常用操作

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/bondsui/article/details/82563219

json介绍

官方介绍:http://golang.org/doc/articles/json_and_go.html

对照关系

go json
bool booleans
float64 numbers
string strings
[]interface{} array
map[string]interface{} objects
nil null

注意事项

  • 结构体的私有字段(小写字段不会被编解码)

  • json tag,struct字段中的别名

  • json 对象的 key 必须是字符串

  • 解码Unmarshal传递的字段是指针

strust字段

type Response struct {
Code int json:"code" //Code进行编码时在json中会以code进行显示和解析
Msg string json:"msg"
Data interface{} json:"data"
time string //私有字段不会被json解析,解析时会隐藏该字段
}

编解码 Marshal

  • func Marshal(v interface{}) ([]byte, error)

  • func MarshalIndent(v interface{}, prefix, indent string) ([]byte, error)

    编码为json字符串,结构体私有字段名称不会进行编解码

type Response struct {
    Code int         `json:"code"`  //字段标签json中的tag,可选
    Msg  string      `json:"msg"`
    Data interface{} `json:"data"`
    time string      //私有字段不会被json解析
}

func main() {
    resp := Response{Code: 9999, Msg: "成功", Data: "bings",time:"1996"}
    if data, err := json.Marshal(resp); err == nil {
        fmt.Printf("%s", data)
    }
}
输出:{"code":9999,"msg":"成功","data":"bings"}

如果输出内容较长,不容易阅读,可使用方法2进行输出格式化

if data, err := json.MarshalIndent(resp,"","\t"); err == nil {
        fmt.Printf("%s", data)
}
输出结果为
{
    "code": 9999,
    "msg": "成功",
    "data": "bings"
}

Unmarshal

  • func Unmarshal(data []byte, v interface{}) error

    解码为struct 私有字段不会进行json编解码

type Response struct {
    Code int         `json:"code"`
    Msg  string      `json:"msg"`
    Data interface{} `json:"data"`
    time string      //私有字段不会被json解析
}

func main() {
    jsonString := "{\"code\":9999,\"msg\":\"成功\",\"data\":\"bings\",\"time\":\"1997\"}"
    var resp Response
    err := json.Unmarshal([]byte(jsonString), &resp)
    if err == nil {
        fmt.Println(resp)
    }
}
输出 {9999 成功 bings }

猜你喜欢

转载自blog.csdn.net/bondsui/article/details/82563219
今日推荐