# 类型错误：datetime类型的对象无法JSON序列化

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

## 根因

在Flask路由中直接返回datetime或其他不可序列化的对象，而没有转换为字符串或使用自定义编码器。

## 版本兼容性

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

## 解决方案

1. **** (95% 成功率)
   ```
   Define a custom JSON encoder: class CustomEncoder(json.JSONEncoder):\n    def default(self, obj):\n        if isinstance(obj, datetime):\n            return obj.isoformat()\n        return super().default(obj)\napp.json_encoder = CustomEncoder
   ```
2. **** (90% 成功率)
   ```
   Convert datetime to ISO format manually: return jsonify({'time': datetime.now().isoformat()})
   ```

## 无效尝试

- **** — Using str(datetime) converts to a string but loses formatting and may cause inconsistent output. (50% 失败率)
- **** — Setting app.json_encoder = None does not fix the issue and may break other serialization. (40% 失败率)
