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

- **ID:** `go/json-cannot-unmarshal-object-into-go-value-of-type-slice`
- **领域:** go
- **类别:** encoding_error
- **验证级别:** ai_generated
- **修复率:** 92%

## 根因

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

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| Go 1.20 | active | — | — |
| Go 1.21 | active | — | — |
| Go 1.22 | active | — | — |

## 解决方案

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] == '[' { ... }
   ```

## 无效尝试

- **** — UseNumber() only affects number decoding, not structural type mismatches like object vs slice. (80% 失败率)
- **** — If the JSON is an array, wrapping in a struct will cause a different mismatch; the fix must match the actual JSON structure. (50% 失败率)
- **** — RawMessage just delays the error; you still need to unmarshal into the correct type later. (60% 失败率)
