Golang struct 变量类型后加类似 `json:"…"` 的形式指的是什么?

2015-09-05 13:18:00 +08:00
 zeroday
最近在看 golang 的代码,看到这么一段

```go
type ContainerStats struct {
// The time of this stat point.
Timestamp time.Time `json:"timestamp"`
Cpu CpuStats `json:"cpu,omitempty"`
DiskIo DiskIoStats `json:"diskio,omitempty"`
Memory MemoryStats `json:"memory,omitempty"`
Network NetworkStats `json:"network,omitempty"`

}
```

请问 类型后 `json:"…"` 的形式指的是什么?
1553 次点击
所在节点    Go 编程语言
10 条回复
lostarry
2015-09-05 13:30:39 +08:00
beyondsoft
2015-09-05 14:31:20 +08:00
Field appears in JSON as key "myName".
wayn3h0
2015-09-05 14:43:19 +08:00
@zeroday

JSON 序列化和反序列化 的 key

Timestamp time.Time `json:"timestamp"` 指定了 key, 序列化后 key 为 timestamp
Timestamp time.Time 未指定 key, 序列化后 key 为 Timestamp
Zzzzzzzzz
2015-09-05 14:50:00 +08:00
反射 Tag, Go 在运行时可以取到, 然后根据这个再处理具体业务, 比如表单的 field 、 数据表的 column 以及这个例子里的 json 字段, 但是这个特性一旦滥用拉性能拉得厉害.
lynx
2015-09-05 15:11:24 +08:00
参见 http://pkg.golang.org/pkg/reflect/#StructTag.Get

通过反射可以获取 tag 的值
shawngao
2015-09-05 15:37:52 +08:00
变量实际对应的 json 段的 key
mengzhuo
2015-09-05 22:59:52 +08:00
struct 的 tag
可以自己随便编的
比如我写的 sdk 里
ChargeType string `ucloud:"optional"`
datou552211
2015-09-06 10:51:03 +08:00
顺带一句, tag 的性能很拖后退
zeroday
2015-09-06 15:01:20 +08:00
@wayn3h0 谢谢,明白了。
wayn3h0
2015-09-09 19:37:24 +08:00
@zeroday 不客气 另 omitempty 指定序列化 /反序列化时 可为空

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/218379

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX