分享
  1. 首页
  2. 文章

go struct 与 json

stonekun · · 1782 次点击 · · 开始浏览
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

go struct 与 json

https://golang.org/pkg/encoding/json/#pkg-index

成员标签-tag

https://sosedoff.com/2016/07/16/golang-struct-tags.html

Only data structures that can be represented as valid JSON will be encoded:
JSON objects only support strings as keys; to encode a Go map type it must be of the form map[string]T (where T is any Go type supported by the json package).
// JSON的key只能是string类型,所有在支持Map的情况下,需要其对应的Map的key是string类型。
Channel, complex, and function types cannot be encoded.
// 这些类型是无法被encoded的
Cyclic data structures are not supported; they will cause Marshal to go into an infinite loop.
// 循环数据类型无法被encoded
Pointers will be encoded as the values they point to (or 'null' if the pointer is nil).
// 指针类型可以被encoded
The json package only accesses the exported fields of struct types (those that begin with an uppercase letter). Therefore only the the exported fields of a struct will be present in the JSON output.
// 只能访问那些exported的struct types类型的field(大写字母开头的)

使用

encode

使用marshal方法进行编码。

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

举例使用一个go定义的一个structure Message

type Message struct {
 Name string
 Body string
 Time int64
}

使用一个Message的实例被编码完以后的结果类似于下面

b == []byte(`{"Name":"Alice","Body":"Hello","Time":1294706395881547000}`)

编码中需要注意的内容

Only data structures that can be represented as valid JSON will be encoded:

JSON objects only support strings as keys; to encode a Go map type it must be of the form map[string]T (where T is any Go type supported by the json package).

// JSON的key只能是string类型,所有在支持Map的情况下,需要其对应的Map的key是string类型。

Channel, complex, and function types cannot be encoded.

// 这些类型是无法被encoded的

Cyclic data structures are not supported; they will cause Marshal to go into an infinite loop.

// 循环数据类型无法被encoded

Pointers will be encoded as the values they point to (or 'null' if the pointer is nil).

// 指针类型可以被encoded

The json package only accesses the exported fields of struct types (those that begin with an uppercase letter). Therefore only the the exported fields of a struct will be present in the JSON output.

// 只能访问那些exported的struct types类型的field(大写字母开头的)

decode

https://blog.golang.org/json-and-go


有疑问加站长微信联系(非本文作者)

本文来自:简书

感谢作者:stonekun

查看原文:go struct 与 json

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

关注微信
1782 次点击
添加一条新回复 (您需要 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传

用户登录

没有账号?注册
(追記) (追記ここまで)

今日阅读排行

    加载中
(追記) (追記ここまで)

一周阅读排行

    加载中

关注我

  • 扫码关注领全套学习资料 关注微信公众号
  • 加入 QQ 群:
    • 192706294(已满)
    • 731990104(已满)
    • 798786647(已满)
    • 729884609(已满)
    • 977810755(已满)
    • 815126783(已满)
    • 812540095(已满)
    • 1006366459(已满)
    • 692541889

  • 关注微信公众号
  • 加入微信群:liuxiaoyan-s,备注入群
  • 也欢迎加入知识星球 Go粉丝们(免费)

给该专栏投稿 写篇新文章

每篇文章有总共有 5 次投稿机会

收入到我管理的专栏 新建专栏