doyp9057 2018-02-15 08:20
浏览 688
已采纳

如何使用bigints封送JSON?

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条回答 默认 最新

  • douaoli5328 2018-02-15 08:52
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 有没有帮写代码做实验仿真的
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥30 vmware exsi重置后登不上
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?