Files
hsa/Html/apps/utils/json_serializer.py
2025-12-10 15:10:37 +08:00

59 lines
1.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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)