Golang 中的 json 与嵌套结构体
2022/4/20 6:16:26
本文主要是介绍Golang 中的 json 与嵌套结构体,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
go 中 Marshal 嵌套结构体的结果,与普通结构体所得的结果是不同的。
首先看看示例的结构体定义:
type Inner struct { Info string `json:"info"` } type Outer1 struct { Value Inner `json:"inner"` Title string `json:"title"` } type Outer2 struct { Value string `json:"inner"` Title string `json:"title"` }
Outer1
中用 Inner
类型存储变量 Value
,Outer2
中则是用 string
。
如果我们需要在两个结构体中嵌套 Inner
,那么它们的赋值方式是不一样的:
func main() { inner := Inner{Info: "this is b"} outer1 := Outer1{Title: "this is title", Value: inner} temp, _ := json.Marshal(inner) outer2 := Outer2{Title: "this is title", Value: string(temp)} res1, _ := json.Marshal(outer1) fmt.Println(string(res1)) res2, _ := json.Marshal(outer2) fmt.Println(string(res2)) }
输出结果如下:
{"b":{"info":"this is b"},"title":"this is title"} {"b":"{\"info\":\"this is b\"}","title":"this is title"}
对于这两种结构体,可以看出:
- 当对「内嵌的结构体」去 marshal 时,解出来的子结构体是不带转义的
- 对于「使用 string 保存,子结构体 marshal 后字符串」的,解出来的子结构体是自带转义的
这篇关于Golang 中的 json 与嵌套结构体的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-30React Native常用组件-点击组件
- 2024-05-30uniapp+vue3+uv-ui手机端后台OA管理模板
- 2024-05-29Python网络爬虫的时候json=就是让你少写个json.dumps()
- 2024-05-27React Native常用组件-展示组件
- 2024-05-27React Native常用组件-列表组件
- 2024-05-09vue3开发前端表单缓存自定义指令,移动端h5必备插件
- 2024-05-09React Hooks在class组件中的使用方式
- 2024-03-30[OIDC in Action] 2. 基于OIDC(OpenID Connect)的SSO(纯JS客户端)
- 2024-03-29terraform jsonencode
- 2024-03-13vuex-persist