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 类型存储变量 ValueOuter2 中则是用 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 后字符串」的,解出来的子结构体是自带转义
posted @   KawaiHe  阅读(2379)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示
主题色彩