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,文章来源:https://www.toymoban.com/news/detail-701383.html
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"}}文章来源地址https://www.toymoban.com/news/detail-701383.html
到了这里,关于golang 多个struct 转换融合为一个json,平级融合或者多级融合的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!