go
data_error
ai_generated
true
json:无法将数字反序列化到 Go 结构体字段 User.age(类型 string)
json: cannot unmarshal number into Go struct field User.age of type string
ID: go/json-cannot-unmarshal-number-into-string
80%修复率
87%置信度
0证据数
2024-05-02首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 1.18 | active | — | — | — |
| 1.22 | active | — | — | — |
根因分析
JSON 负载在 Go 结构体期望 string 的位置包含了数字。可能是 API 变更或结构体字段声明错误。
English
The JSON payload contains a numeric value where the Go struct expects a string. The API changed, or the schema was misdeclared.
解决方案
-
88% 成功率
type User struct { Age json.Number `json:"age"` } dec := json.NewDecoder(r) dec.UseNumber() dec.Decode(&u) -
85% 成功率
Define a custom type with UnmarshalJSON that accepts both string and number.
无效尝试
常见但无效的做法:
-
60% 失败
Loses type safety and just moves the panic downstream when the value is used.
-
75% 失败
Leaves partially populated struct and hides real data corruption.