golang中的json解析

2018-04-19  本文已影响0人  youngyezi

json 解码

首先我们构建一个常用的接口返回的json数据格式

//某api接口返回数据:
    {
        "code": 200,
        "msg": "success",
        "data": {
            "title": "w2le",
            "content": "golang中的json解析",
            "url": "www.w2le.com"
        }
    } 

main.go

package main
import (
    "fmt"
    "github.com/pquerna/ffjson/ffjson"
)
type (
    //定义外层response结构体
    Response struct {
        Code int    `json:"code"`
        Msg  string `json:"msg"`
        Data Data   `json:"data"` //嵌套Data 结构体
    }
    //定义Data层结构体
    Data struct {
        Title   string `json:"title"`
        Content string `json:"content"`
        Url     string `json:"url"`
    }
)
func main() {
    data := "{\"code\": 200,\"msg\": \"success\", \"date\": {\"title\": \"w2le\", \"content\":  \"golang\u4e2d\u7684json\u89e3\u6790\", \"url\": \"www.w2le.com\"}}"
    res := &Response{}
    ffjson.Unmarshal([]byte(data), res)
    fmt.Println(res)
}
// output : &{200 success {w2le golang中的json解析 www.w2le.com}} 

Golang解析json时候,多维数组需要一层一层定义数据结构,然后嵌套

  json:"field"
//字段后面的 json语法。是指定解析field
//定义struct时候注意首字母大写
//Go中用首字母大小写来区分 public 和 private

json 编码

func main() {
    r, err := ffjson.Marshal(res)
    if err != nil {
    log.Println(err)
    }
    fmt.Println(string(r))
}
//output :  {"code":0,"msg":"success","date":{"title":"w2le","content":"golang中的json解析","url":"www.w2le.com"}}
//ffjson.Marshal(res) 返回的数据(r) 是 []byte类型

原文来自: golang中的json解析

更多相关详细内容请移步 w2le.com
关注w2le.com 关注web开发

上一篇下一篇

猜你喜欢

热点阅读