go
type_error
ai_generated
true
错误:json:调用time.Duration类型的MarshalJSON时出错
error: json: error calling MarshalJSON for type time.Duration
ID: go/encoding-json-marshal-time-duration
80%修复率
81%置信度
0证据数
2026-11-15首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 1.20 | active | — | — | — |
| 1.21 | active | — | — | — |
根因分析
time.Duration未实现json.Marshaler,会被编组为纳秒整数,可能不符合预期。
English
time.Duration does not implement json.Marshaler and is marshaled as a nanosecond integer, which may not be intended.
解决方案
-
90% 成功率 Create a custom type that marshals duration as string
type Duration time.Duration func (d Duration) MarshalJSON() ([]byte, error) { return json.Marshal(time.Duration(d).String()) }
无效尝试
常见但无效的做法:
-
Using string formatting to convert duration
60% 失败
Inconsistent output; use custom type with MarshalJSON.