序列化

This commit is contained in:
CakeCN
2025-12-10 15:10:37 +08:00
parent 36662654ba
commit abf6f3aa2f
4 changed files with 232 additions and 1 deletions

View File

@@ -0,0 +1,58 @@
import json
from datetime import datetime, date, time
from bson import ObjectId
from typing import Any, Dict, List, Union
class JSONEncoder(json.JSONEncoder):
"""
通用JSON编码器处理常见的非JSON序列化类型
支持的特殊类型:
- datetime: 转换为ISO格式字符串
- date: 转换为ISO格式字符串
- time: 转换为ISO格式字符串
- ObjectId: 转换为字符串
- 其他不可序列化类型: 转换为字符串表示
"""
def default(self, obj: Any) -> Any:
if isinstance(obj, (datetime, date, time)):
return obj.isoformat()
elif isinstance(obj, ObjectId):
return str(obj)
elif isinstance(obj, bytes):
return obj.decode('utf-8', errors='replace')
elif isinstance(obj, (set, frozenset)):
return list(obj)
elif hasattr(obj, '__dict__'):
return obj.__dict__
else:
return str(obj)
def json_serialize(obj: Any) -> str:
"""
通用JSON序列化函数处理常见的非JSON序列化类型
参数:
- obj: 要序列化的对象
返回:
- str: JSON字符串
"""
return json.dumps(obj, cls=JSONEncoder, ensure_ascii=False)
def json_serialize_dict(obj: Any) -> Dict:
"""
通用JSON序列化函数将对象转换为可JSON序列化的字典
参数:
- obj: 要序列化的对象
返回:
- Dict: 可JSON序列化的字典
"""
json_str = json_serialize(obj)
return json.loads(json_str)