go encoding_error ai_generated true

json: 无法将对象反序列化为 Go 值类型 []main.Foo

json: cannot unmarshal object into Go value of type []main.Foo

ID: go/json-cannot-unmarshal-object-into-go-value-of-type-slice

其他格式: JSON · Markdown 中文 · English
92%修复率
86%置信度
1证据数
2023-08-05首次发现

版本兼容性

版本状态引入弃用备注
Go 1.20 active
Go 1.21 active
Go 1.22 active

根因分析

JSON 输入是一个对象(例如 {}),但目标 Go 类型是切片,导致反序列化期间类型不匹配。

English

JSON input is an object (e.g., {}) but the target Go type is a slice, causing a type mismatch during unmarshaling.

generic

官方文档

https://pkg.go.dev/encoding/json#UnmarshalTypeError

解决方案

  1. Change the target type to a struct that matches the JSON object: type Foo struct { ... } then unmarshal into &foo.
  2. If the JSON is expected to be an array, fix the JSON source to output an array instead of an object.
  3. Use json.RawMessage to inspect the JSON structure first, then unmarshal conditionally: var raw json.RawMessage; json.Unmarshal(data, &raw); if raw[0] == '{' { ... } else if raw[0] == '[' { ... }

无效尝试

常见但无效的做法:

  1. 80% 失败

    UseNumber() only affects number decoding, not structural type mismatches like object vs slice.

  2. 50% 失败

    If the JSON is an array, wrapping in a struct will cause a different mismatch; the fix must match the actual JSON structure.

  3. 60% 失败

    RawMessage just delays the error; you still need to unmarshal into the correct type later.