How to marshal JSON with bigints?

£可爱£侵袭症+ 提交于 2019-12-11 02:43:47

问题


I have a json that contains a field with a bigint

{"NETWORK_ID": 6000370005980500000071}

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() seems to be for this purpose but it's only for decoding I think.

Is there any way that I can detect this kind of bigint number and make them serialize as strings?


回答1:


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.



来源:https://stackoverflow.com/questions/48802728/how-to-marshal-json-with-bigints

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!