golang struct json tag的使用以及深入讲解
本篇文章给大家分享《golang struct json tag的使用以及深入讲解》,覆盖了Golang的常见基础知识,其实一个语言的全部知识点一篇文章是不可能说完的,但希望通过这些问题,让读者对自己的掌握程度有一定的认识(B 数),从而弥补自己的不足,更好的掌握它。
一、sturct json tag的使用
1.tag格式说明
struct json tag主要在struct与json数据转换的过程(Marshal/Unmarshal)中使用。
json的tag格式如下:
Key type `json:"name,opt1,opt2,opts..."`
说明:
- 变量必须是可导出的(Key首字母必须大写),否则会被忽略处理。
- 没有json tag或者tag中name省略(但不能少了","),默认使用字段名。
- name要注意命名的有效性。
- opt1、opt2等项为可选项,必须使用有限的几个限定的opt的一个或组合,如"omitempty"、"string",使用非限定的opt会发生错误。
2.具体使用格式说明
我们先介绍下源码文档中提供的几种使用方式:
因Marshal与Unmarshal是相反的过程,两者规则是一致的,以下介绍中仅说明了Marshal时的处理。
(1)不指定tag
Field int // “Filed”:0
不指定tag,默认使用变量名称。转换为json时,key为Filed。
(2)直接忽略
Field int json:"-" //注意:必须为"-",不能带有opts
转换时不处理。
(3)指定key名
Field int json:"myName" // “myName”:0
转换为json时,key为myName
(4)"omitempty"零值忽略
Field int json:",omitempty"
转换为json时,值为零值则忽略,否则key为myName
(5)指定key且零值忽略
Field int json:"myName,omitempty"
转换为json时,值为零值则忽略,否则key为myName
(6)指定key为"-"
Field int json:"-," // “-”:0
此项与忽略的区别在于多了个”,“。
(7)“string” opt
以上提到的用法都是常见的,这个比较特殊。
"string"仅适用于字符串、浮点、整数或布尔类型,表示的意思是:将字段的值转换为字符串;解析时,则是将字符串解析为指定的类型。主要用于与javascript通信时数据的转换。
注意:
仅且仅有"string",没有int、number之类的opt。即带"string" opt的字段,编码时仅能将字符串、浮点、整数或布尔类型转换为string类型,反之则不然;解码时可以将string转换为其他类型,反之不然。因为"string"有限制。
Int64String int64 json:",string" // “Int64String”:“0”
“string” opt的使用可以在Marshal/Unmarshal时自动进行数据类型的转换,减少了手动数据转换的麻烦,但是一定要注意使用的范围,对不满足的类型使用,是会报错的。
猜下对string使用"string" opt的结果会是如何呢?
Int64String string json:",string"
我们在了解源码后解答。
二、源码角度的设计处理过程
一切的使用方式肯定在设计时就已限定,我们现在看看源码中的处理过程。
在看实现的过程中,可以思考下使用的方式对不对,还有要注意的地方吗?
对某些地方非常好的实现思路,我们也可以借鉴下,对以后的编程学习大有裨益。
此处为了简洁,具体调用过程略过不讲,直接查看核心代码部分,有兴趣的话,可以查看下完整过程。
1.typeFields
在typeFields中详细的对上面提到的各种用法的tag做了处理,处理后的数据存入fileds,最后在进行编码。
// typeFields returns a list of fields that JSON should recognize for the given type.
// The algorithm is breadth-first search over the set of structs to include - the top struct
// and then any reachable anonymous structs.
func typeFields(t reflect.Type) structFields {
// Anonymous fields to explore at the current level and the next.
current := []field{}
next := []field{{typ: t}}
// Count of queued names for current level and the next.
var count, nextCount map[reflect.Type]int
// Types already visited at an earlier level.
visited := map[reflect.Type]bool{}
// Fields found.
var fields []field
// Buffer to run HTMLEscape on field names.
var nameEscBuf bytes.Buffer
for len(next) > 0 {
current, next = next, current[:0]
count, nextCount = nextCount, map[reflect.Type]int{}
for _, f := range current {
if visited[f.typ] {//已处理的过类型跳过
continue
}
visited[f.typ] = true
// Scan f.typ for fields to include.
for i := 0; i 1 {
// If there were multiple instances, add a second,
// so that the annihilation code will see a duplicate.
// It only cares about the distinction between 1 or 2,
// so don't bother generating any more copies.
fields = append(fields, fields[len(fields)-1])
}
continue
}
// Record new anonymous struct to explore in next round.
nextCount[ft]++
if nextCount[ft] == 1 {
next = append(next, field{name: ft.Name(), index: index, typ: ft})
}
}
}
}
...
for i := range fields {
f := &fields[i]
f.encoder = typeEncoder(typeByIndex(t, f.index))//设置fields的encoder
}
nameIndex := make(map[string]int, len(fields))
for i, field := range fields {
nameIndex[field.name] = i
}
return structFields{fields, nameIndex}
}
2.encode
func newStructEncoder(t reflect.Type) encoderFunc {
se := structEncoder{fields: cachedTypeFields(t)}
return se.encode
}
func (se structEncoder) encode(e *encodeState, v reflect.Value, opts encOpts) {
next := byte('{')
FieldLoop:
for i := range se.fields.list {
f := &se.fields.list[i]
// Find the nested struct field by following f.index.
fv := v
for _, i := range f.index {
if fv.Kind() == reflect.Ptr {
if fv.IsNil() {
continue FieldLoop
}
fv = fv.Elem()
}
fv = fv.Field(i)
}
if f.omitEmpty && isEmptyValue(fv) {//"omitempty"的忽略处理,需要值为零值
continue
}
e.WriteByte(next)
next = ','
if opts.escapeHTML {
e.WriteString(f.nameEscHTML)
} else {
e.WriteString(f.nameNonEsc)
}
opts.quoted = f.quoted
f.encoder(e, fv, opts)//根据具体类型的编码处理
}
if next == '{' {
e.WriteString("{}")
} else {
e.WriteByte('}')
}
}
以下以int类型intEncoder为例:
func intEncoder(e *encodeState, v reflect.Value, opts encOpts) {
b := strconv.AppendInt(e.scratch[:0], v.Int(), 10)
if opts.quoted {//带有"string" opt添加引号
e.WriteByte('"')
}
e.Write(b)
if opts.quoted {
e.WriteByte('"')
}
}
对于数字类型,如果带有**“string”**则在写入正式值前后添加引号。
对于字符串类型,如果带有**“string”**,原string值再编码时会添加引号,再对结果添加引号,则格式异常,因此需要先对原值进行编码。
func stringEncoder(e *encodeState, v reflect.Value, opts encOpts) {
if v.Type() == numberType {
numStr := v.String()
// In Go1.5 the empty string encodes to "0", while this is not a valid number literal
// we keep compatibility so check validity after this.
if numStr == "" {
numStr = "0" // Number's zero-val
}
if !isValidNumber(numStr) {
e.error(fmt.Errorf("json: invalid number literal %q", numStr))
}
e.WriteString(numStr)
return
}
if opts.quoted {
sb, err := Marshal(v.String())//注意此处处理
if err != nil {
e.error(err)
}
e.string(string(sb), opts.escapeHTML)
} else {
e.string(v.String(), opts.escapeHTML)
}
}
func (e *encodeState) string(s string, escapeHTML bool) {
e.WriteByte('"')//添加引号
start := 0
for i := 0; i , and &
// because they can lead to security holes when
// user-controlled strings are rendered into JSON
// and served to some browsers.
e.WriteString(`u00`)
e.WriteByte(hex[b>>4])
e.WriteByte(hex[b&0xF])
}
i++
start = i
continue
}
c, size := utf8.DecodeRuneInString(s[i:])
if c == utf8.RuneError && size == 1 {
if start
在了解完源码的处理过程后,我们对之前提到的问题做个解答。对string类型的字段添加"string" opt,得到的是:
Int64String string json:",string" // “Int64String”: "“1234"”
三、总结
本文主要从源码的角度说明struct json tag的为什么这么使用,以及使用时需要注意的地方。最后重复下重要的几点:
- 字段必须可导出,tag才有意义
- 忽略必须使用json:"-",不得带有opts,否则key将会变成"-"
- "string" opt仅适用于字符串、浮点、整数及布尔类型,意思是可以将这些类型的数据Marshal为string类型,或者将string类型的数据Unmarshal为这些类型。
请勿滥用,尤其是对已经是string类型的数据使用。
以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。
浅谈Go切片的值修改是否会覆盖数组的值
- 上一篇
- 浅谈Go切片的值修改是否会覆盖数组的值
- 下一篇
- GoLang中Json Tag用法实例总结
-
- 凶狠的鸭子
- 这篇博文出现的刚刚好,好细啊,很好,码起来,关注楼主了!希望楼主能多写Golang相关的文章。
- 2023-01-19 03:03:48
-
- Golang · Go教程 | 8小时前 | goroutine · pprof · Go教程 · 运行时 · Go pprof 性能诊断 goroutine profile pprof.Lookup
- Go pprof.Lookup 怎样读取 goroutine profile 文本
- 465浏览 收藏
-
- Golang · Go教程 | 8小时前 | 标准库 · HTTP · Go教程 · Go 请求头 textproto CanonicalMIMEHeaderKey MIMEHeader
- Go textproto.CanonicalMIMEHeaderKey 怎样统一请求头键名
- 283浏览 收藏
-
- Golang · Go教程 | 8小时前 |
- Go image.NewRGBA 怎样创建可修改的 RGBA 画布
- 289浏览 收藏
-
- Golang · Go教程 | 8小时前 |
- Go compress/gzip Reader 怎样复用并正确关闭
- 454浏览 收藏
-
- Golang · Go教程 | 8小时前 |
- Go archive/zip FileHeader.ExternalAttrs 读取条目权限属性
- 460浏览 收藏
-
- Golang · Go教程 | 8小时前 | 标准库 · Go教程 · Go 邮箱地址 net/mail ParseAddressList 收件人列表
- Go net/mail ParseAddressList 怎样解析多个收件人
- 465浏览 收藏
-
- Golang · Go教程 | 8小时前 | Go教程 · Go crypto/rand 随机令牌 随机字节 密钥材料
- Go crypto/rand 怎样生成固定字节数随机值
- 443浏览 收藏
-
- Golang · Go教程 | 8小时前 |
- Go net.Dialer 怎样配置连接建立超时
- 151浏览 收藏
-
- Golang · Go教程 | 8小时前 |
- Go tls.Config 怎样限制最低 TLS 版本
- 197浏览 收藏
-
- Golang · Go教程 | 8小时前 | go · Plugin · Go plugin 版本兼容 buildmode=plugin
- Go plugin 包为什么不适合跨版本加载
- 426浏览 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 485次学习
-
- PubMedQA
- 深入了解PubMedQA生物医学问答数据集,涵盖其核心功能、使用方法及在临床决策、药物研发等场景的应用,助力提升NLP模型性能。
- 609次使用
-
- H2O EvalGPT
- H2O EvalGPT是H2O.ai推出的开源LLM评估平台,提供详细的大模型性能排行榜、行业特定基准测试及A/B测试功能,助您快速选择最适合项目的高性能大语言模型。
- 648次使用
-
- LMArena
- LMArena是加州大学伯克利分校推出的AI模型匿名评测平台。通过盲测投票机制,用户可对比不同大模型回答并生成实时排行榜,助力开发者优化模型及用户选择最佳AI工具。
- 679次使用
-
- HELM
- 深入了解斯坦福推出的HELM(Holistic Evaluation of Language Models)大模型评测体系。本文解析其核心功能、安装配置步骤及应用场景,涵盖准确性、公平性、鲁棒性等多维度指标,助力开发者全面优化语言模型性能。
- 643次使用
-
- MMBench
- MMBench是由上海人工智能实验室等机构联合推出的多模态基准测试平台,提供细粒度能力评估、大规模数据集及VLMEvalKit工具。本文详细介绍其核心功能、安装使用方法及应用场景,助力开发者全面评估多模态模型性能。
- 466次使用
-
- 接口返回 200 但前端仍报错怎么办:从响应格式到跨域一步步排查
- 2026-06-14 332浏览
-
- 详解如何在Go语言中循环数据结构
- 2022-12-22 406浏览
-
- 一文带你搞懂Golang结构体内存布局
- 2022-12-22 125浏览
-
- golang生成JSON以及解析JSON
- 2023-01-17 329浏览
-
- Go如何实现json字符串与各类struct相互转换
- 2023-01-07 377浏览

