golang的json.unmarshall导致int64类型精度损失(仅针对map),使用Decode解决

注意针对map时会丢失精度,struct则不会:

package main

import "encoding/json"

type MS struct {
	Uid int64
}

func main() {
	ms := &MS{
		Uid: 1234567891234567891,
	}
	mss := &MS{}
	msj, _ := json.Marshal(ms)
	_ = json.Unmarshal(msj, mss)
	print(mss) // 打印 {"Uid":1234567891234567891}
}

 精度丢失时:

tmpInstance := &struct {
		SignModel
		Content string  `json:"content,omitempty"`
		FloatV  float64 `json:"floatV,omitempty"`
		ArrV    []int64 `json:"arrV,omitempty"`
		BoolV   bool    `json:"boolV"`
	}{
		SignModel: SignModel{
			ApiKey:    "EuIWWPXyDAUPmuwFxuRukHczNVkWqwUT",
			NonceStr:  "sisnfiskjfnkfosmfiskjfnkfiskjfnk",
			TimeStamp: 1609826705,
			Sign:      "123",
		},
		Content: "我是一段Content文字,我是一段Content文字,我是一段Content文字。。。",
		FloatV:  0.1,              // 在GenStr函数内转成了:"0.1"
		ArrV:    []int64{1, 2, 3, 123456789123456789}, // 在GenStr函数内转成了:"[1,2,3]"
		BoolV:   true,             // 在GenStr函数内转成了:"true"
	}

	interfaceMap := make(map[string]interface{}, 0)
	interfaceJson, _ := json.Marshal(tmpInstance)
	if err := json.Unmarshal(interfaceJson, &interfaceMap); err != nil {
		t.Fatalf("[gateway] VerifySign json.Unmarshal(interfaceJson, &interfaceMap) err: %v", err)
	}

最后interfaceMap里的ArrV参数的第四项是123456789123456780,损失了精度

可以使用 Decode 代替unmarshall来解决

dec := json.NewDecoder(bytes.NewBuffer(str))
 dec.UseNumber()//关键步骤
 _ = dec.Decode(&mapS)
 fmt.Println(mapS)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值