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 后字符串」的,解出来的子结构体是自带转义的