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>


