当前位置:首页 > golang中的json解析

golang中的json解析

发布于 2018-04-11 阅读 2876 次 Golang

简介

golang 原生提供了 encoding/json 的json处理包
而此次准备通过github 的第三方包(github.com/pquerna/ffjson/ffjson)来处理json的编解码

json 解码

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

  1. //某api接口返回数据:
  2. {
  3. "code": 200,
  4. "msg": "success",
  5. "data": {
  6. "title": "w2le",
  7. "content": "golang中的json解析",
  8. "url": "www.w2le.com"
  9. }
  10. }

main.go

  1. package main
  2. import (
  3. "fmt"
  4. "github.com/pquerna/ffjson/ffjson"
  5. )
  6. type (
  7. //定义外层response结构体
  8. Response struct {
  9. Code int `json:"code"`
  10. Msg string `json:"msg"`
  11. Data Data `json:"data"` //嵌套Data 结构体
  12. }
  13. //定义Data层结构体
  14. Data struct {
  15. Title string `json:"title"`
  16. Content string `json:"content"`
  17. Url string `json:"url"`
  18. }
  19. )
  20. func main() {
  21. data := "{\"code\": 200,\"msg\": \"success\", \"date\": {\"title\": \"w2le\", \"content\": \"golang\u4e2d\u7684json\u89e3\u6790\", \"url\": \"www.w2le.com\"}}"
  22. res := &Response{}
  23. ffjson.Unmarshal([]byte(data), res)
  24. fmt.Println(res)
  25. }
  26. // output : &{200 success {w2le golang中的json解析 www.w2le.com}}

Golang解析json时候,多维数组需要一层一层定义数据结构,然后嵌套
json:"field"用来指定解析字段field

json 编码

main.go

  1. func main() {
  2. r, err := ffjson.Marshal(res)
  3. if err != nil {
  4. log.Println(err)
  5. }
  6. fmt.Println(string(r))
  7. }
  8. //output : {"code":0,"msg":"success","date":{"title":"w2le","content":"golang中的json解析","url":"www.w2le.com"}}

ffjson.Marshal(res) 返回的数据(r) 是 []byte类型