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

MarshalJSON具有嵌入式类型的类型最终以{}代替值

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

MarshalJSON具有嵌入式类型的类型最终以{}代替值

big.Int
实现自定义JSON
marshaler(
json.Marshaler
),请参见
Int.MarshalJSON()
。但是此方法具有指针接收器,因此只有在具有指针值:时,才使用/调用该方法
*big.Int

并且您嵌入了一个非指针值,因此不会调用此自定义封送拆收器,并且由于

big.Int
它是具有未导出字段的结构,因此您将在输出中看到一个空的JSON对象:
{}

为了使其工作,您应该使用指向您的类型的指针,例如:

Amount      *utils.BigInt `json:"amount,omitempty"`Fee         *utils.BigInt `json:"fee,omitempty"`

使用它的示例:

s := SpendTx{    SenderID:    "alice",    RecipientID: "bob",    Amount:      &utils.BigInt{},    Fee:         &utils.BigInt{},}data, err := s.JSON()fmt.Println(string(data), err)

然后以输出为例(在Go Playground上尝试):

{"sender_id":"alice","recipient_id":"bob","amount":0,"fee":0} <nil>

另一个选择是使用non-pointer

utils.BigInt
,但是
utils.BigInt
应该嵌入一个指针类型:

type BigInt struct {    *big.Int}type SpendTx struct {    Amount      utils.BigInt `json:"amount,omitempty"`    Fee         utils.BigInt `json:"fee,omitempty"`}

然后使用它:

s := SpendTx{    SenderID:    "alice",    RecipientID: "bob",    Amount:      utils.BigInt{new(big.Int)},    Fee:         utils.BigInt{new(big.Int)},}data, err := s.JSON()fmt.Println(string(data), err)

再次输出(在Go Playground上尝试):

{"sender_id":"alice","recipient_id":"bob","amount":0,"fee":0} <nil>


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

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

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