1. 平级融合,就是下面例子,虽然A在B里面,但是A在struct B里面没有名字,输出结果就是A 和B在同一级的json下面。
- package main
-
- import (
- "encoding/json"
- "fmt"
- )
-
- type A struct {
- Name string `json:"name"`
- Description string `json:"description"`
- URL string `json:"url"`
- }
-
- type B struct {
- Name string `json:"name"`
- *A
- }
-
- func main() {
- a := A{Name: "test", Description: "desc", URL: "https://example.com"}
- b := B{Name: "new name"}
-
- b.A = &a
-
- data, _ := json.Marshal(b)
-
- fmt.Println(string(data))
- }
输出:{"name":"new name","description":"desc","url":"https://example.com"}
2. 两级json,
- package main
-
- import (
- "encoding/json"
- "fmt"
- )
-
- type A struct {
- Name string `json:"name"`
- Description string `json:"description"`
- URL string `json:"url"`
- }
-
- type B struct {
- Name string `json:"name"`
- Adata *A
- }
-
- func main() {
- a := A{Name: "test", Description: "desc", URL: "https://example.com"}
- b := B{Name: "new name"}
-
- b.Adata = &a
-
- data, _ := json.Marshal(b)
-
- fmt.Println(string(data))
- }
输出:{"name":"new name","Adata":{"name":"test","description":"desc","url":"https://example.com"}}