# TypeError: User 类型的对象无法进行 JSON 序列化

- **ID:** `python/sqlalchemy-json-serialization-error`
- **领域:** python
- **类别:** type_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

尝试直接用 json.dumps() 序列化 SQLAlchemy 模型实例，而没有自定义编码器。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 1.4.x | active | — | — |
| 2.0.x | active | — | — |

## 解决方案

1. **** (90% 成功率)
   ```
   Use a custom encoder: class UserEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, User): return {'id': obj.id, 'name': obj.name} return super().default(obj)
   ```
2. **** (85% 成功率)
   ```
   Convert to dict first: user_dict = {c.name: getattr(user, c.name) for c in user.__table__.columns}
   ```

## 无效尝试

- **** — Returns the object's string representation, not the data. (80% 失败率)
- **** — Converts all non-serializable objects to strings, losing structure. (70% 失败率)
