33
golang面试题:json包变量不加tag会怎么样?
source link: https://studygolang.com/articles/29281
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
image
问题
json
包里使用的时候,结构体里的变量不加 tag
能不能正常转成 json
里的字段?
怎么答
-
如果变量
首字母小写
,则为private
。无论如何不能转
,因为取不到反射信息
。 -
如果变量
首字母大写
,则为public
。-
不加tag
,可以正常转为json
里的字段,json
内字段名跟结构体内字段原名一致
。 -
加了tag
,从struct
转json
的时候,json
的字段名就是tag
里的字段名,原字段名已经没用。
-
举例
通过一个例子加深理解。
package main import ( "encoding/json" "fmt" ) type J struct { a string //小写无tag b string `json:"B"` //小写+tag C string //大写无tag D string `json:"DD"` //大写+tag } func main() { j := J { a: "1", b: "2", C: "3", D: "4", } fmt.Printf("转为json前j结构体的内容 = %+v\n", j) jsonInfo, _ := json.Marshal(j) fmt.Printf("转为json后的内容 = %+v\n", string(jsonInfo)) }
输出
转为json前j结构体的内容 = {a:1 b:2 C:3 D:4} 转为json后的内容 = {"C":"3","DD":"4"}
解释
- 结构体里定义了四个字段,分别对应
小写无tag
,小写+tag
,大写无tag
,大写+tag
。 - 转为
json
后首字母小写的
不管加不加tag都不能
转为json
里的内容,而大写的
加了tag
可以取别名
,不加tag
则json
内的字段跟结构体字段原名一致
。
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK