栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在Go中的嵌入式结构上实现json marshaller

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在Go中的嵌入式结构上实现json marshaller

由于

MarshalJSON
匿名字段的方法
*meta
将提升为
MyStruct
,因此在
encoding/json
将MyStruct编组后,程序包将使用该方法。

您可以做的是,您可以像这样在MyStruct上

meta
实现
Marshaller
接口,而不是让其实现接口:

package mainimport (    "fmt"    "encoding/json"    "strconv")type MyStruct struct {    *meta    Contents []interface{}}type meta struct {    Id int}func (m *MyStruct) MarshalJSON() ([]byte, error) {    // Here you do the marshalling of meta    meta := `"Id":` + strconv.Itoa(m.meta.Id)    // Manually calling Marshal for Contents    cont, err := json.Marshal(m.Contents)    if err != nil {        return nil, err    }    // Stitching it all together    return []byte(`{` + meta + `,"Contents":` + string(cont) + `}`), nil}func main() {    str := &MyStruct{&meta{Id:42}, []interface{}{"MyForm", 12}}    o, err := json.Marshal(str)    if err != nil {        panic(err)    }    fmt.Println(string(o))}

{“ Id”:42,“ Contents”:[“ MyForm”,12]}

操场



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/417782.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号