← 中文资源

简体中文版本

JSON int64 溢出解码错误

把 MaxInt64+1 解进 int64 字段会得到 UnmarshalTypeError,同行的 uint64 字段却能照常收下,失败字段保持零值。

阅读英文原文

实现说明

JSON int64 溢出解码错误可以归结为函数 main。

使用要点

  • 每一步打印都带着自己的标签:decode error:、field、user_id:。

常见问题

运行「JSON int64 溢出解码错误」会打印什么?

文件本身就是完整程序,直接运行——输出行带有 decode error:、field、user_id: 这类标签。

核心语句

payload := []byte(`{"user_id":9223372036854775808,"leader_id":9223372036854775808}`)

代码示例

package main

import (
	"encoding/json"
	"errors"
	"fmt"
)

type Session struct {
	UserID   int64  `json:"user_id"`
	LeaderID uint64 `json:"leader_id"`
}

func main() {
	// 9223372036854775808 = MaxInt64 + 1: overflow for int64, fits uint64
	payload := []byte(`{"user_id":9223372036854775808,"leader_id":9223372036854775808}`)

	var session Session
	err := json.Unmarshal(payload, &session)

	var typeErr *json.UnmarshalTypeError
	fmt.Println("decode error:", errors.As(err, &typeErr))
	if typeErr != nil {
		fmt.Printf("field %s value %s does not fit %s\n", typeErr.Field, typeErr.Value, typeErr.Type)
	}

	// the rejected field stays zero; the representable one decodes anyway
	fmt.Println("user_id:", session.UserID)
	fmt.Println("leader_id:", session.LeaderID)
}