golang的json.unmarshall导致int64类型精度损失,使用Decode解决

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)

猜你喜欢

转载自blog.csdn.net/chushoufengli/article/details/114393123