如何使用bigints封送JSON? [英] How to marshal JSON with bigints?
问题描述
我有一个json
,其中包含带有bigint
I have a json
that contains a field with a bigint
{"NETWORK_ID": 6000370005980500000071}
在编组之前我使用的格式是map[string]interface{}
The format I have before marshaling is map[string]interface{}
当我将其编组并打印以进行控制台时,一切似乎都很好,但是由于其在其他介质中的大小,该字段实际上会产生问题,因此我想将其序列化为字符串.
When I marshal it and print to console everything seems to be fine but this field actually creates problems due to its size in other mediums so I want to serialize it as a string.
UseNumber()
似乎是用于此目的,但我认为它仅用于解码.
UseNumber()
seems to be for this purpose but it's only for decoding I think.
有什么方法可以检测到这种bigint
数字并将其序列化为字符串吗?
Is there any way that I can detect this kind of bigint
number and make them serialize as strings?
推荐答案
You'll need to create a custom type that implements the json.Marshaler interface, and marshals to a string. Example:
type MyBigInt big.Int
func (i MyBigInt) MarshalJSON() ([]byte, error) {
i2 := big.Int(i)
return []byte(fmt.Sprintf(`"%s"`, i2.String()), nil
}
这将始终将您的自定义类型编组为带引号的十进制数字.
This will always marshal your custom type as a quoted decimal number.
这篇关于如何使用bigints封送JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!