# TypeError: 类型 'User' 的对象不是 JSON 可序列化的

- **ID:** `python/fastapi-typeerror-object-of-type-type-is-not-json-serializable`
- **领域:** python
- **类别:** type_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

直接从端点返回自定义 Python 对象，而未转换为 JSON 可序列化格式。

## 版本兼容性

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

## 解决方案

1. **Use a Pydantic model for the response.** (95% 成功率)
   ```
   from pydantic import BaseModel
class UserOut(BaseModel):
    id: int
    name: str

@app.get('/users/{user_id}', response_model=UserOut)
async def get_user(user_id: int):
    user = get_user_from_db(user_id)
    return UserOut(id=user.id, name=user.name)
   ```
2. **Convert the object to a dictionary manually.** (90% 成功率)
   ```
   @app.get('/users/{user_id}')
async def get_user(user_id: int):
    user = get_user_from_db(user_id)
    return {'id': user.id, 'name': user.name}
   ```

## 无效尝试

- **Using json.dumps() on the object directly.** — json.dumps() also requires a serializable object; custom objects need a custom encoder. (70% 失败率)
- **Returning the object without a response model.** — FastAPI tries to serialize the object automatically but fails if it's not a dict or Pydantic model. (80% 失败率)
