# -*- coding:utf8 -*-
# Time : 2020/10/10 17:37
# Author : Tian
# File : JsonUtil.py
from __future__ import annotations
import simplejson
class JsonObject(object):
_value: dict
def __init__(self, value):
self._value = value
@staticmethod
def parse(value) -> JsonObject:
"""
将value解析为JsonObject,目前支持的value类型和值为:
json格式的字符串;
dict对象的字符串;
dict对象;
自定义对象;
:param value:
:return:
"""
value = _paramCheck(value, JsonObject.__name__)
return JsonObject(value) if len(dict.keys(value)) != 0 else None
def getBoolean(self, key: str) -> bool:
return _JsonTypeUtil.caseToBool(self._value[key])
def getStr(self, key: str) -> str:
return _JsonTypeUtil.caseToStr(self._value[key])
def getInt(self, key: str) -> int:
return _JsonTypeUtil.caseToInt(self._value[key])
def getFloat(self, key: str) -> float:
return _JsonTypeUtil.caseToFloat(self._value[key])
def getJsonObject(self, key: str) -> JsonObject:
return JsonObject.parse(self._value[key])
def getJsonArray(self, key: str) -> JsonArray:
return JsonArray.parse(self._value[key])
def get(self, key):
return self._value[key]
def contains(self, key: str) -> bool:
return key in self._value.keys()
def toJsonStr(self):
return simplejson.dumps(self._value, encoding='utf-8', ensure_ascii=False)
# def add(self, key, value):
# if not self.contains(key):
# self._value[key] = value
class JsonArray:
_value: list
def __init__(self, value):
self._value = value
@staticmethod
def parse(value) -> JsonArray:
"""
将value解析为JsonArray,支持的value类型为:
set、list、tuple、dict、及上述对象格式的字符串;
:param value:
:return:
"""
value = _paramCheck(value, JsonArray.__name__)
return JsonArray(value) if len(value) != 0 else None
def getBoolean(self, index: int) -> bool:
return _JsonTypeUtil.caseToBool(self._value[index])
def getStr(self, index: int) -> str:
return _JsonTypeUtil.caseToStr(self._value[index])
def getInt(self, index: int) -> int:
return _JsonTypeUtil.caseToInt(self._value[index])
def getFloat(self, index: int) -> float:
return _JsonTypeUtil.caseToFloat(self._value[index])
def getJsonObject(self, index: int) -> JsonObject:
return JsonObject.parse(self._value[index])
def getJsonArray(self, index: int) -> JsonArray:
return JsonArray.parse(self._value[index])
def get(self, index):
return self._value[index]
def _paramCheck(value, className):
def objectToJson(obj: object) -> list or dict:
if isinstance(obj, (str, int, float, bool, complex)):
# 数字、布尔、字符串 直接返回
return obj
elif isinstance(obj, dict):
# 字典 遍历,转换value值
for k, v in obj.items():
obj[k] = objectToJson(v)
return obj
elif isinstance(obj, (list, set, tuple)):
# 列表、字典、元组,先转换成列表,再遍历转换值
obj = list(obj)
for i in range(len(obj)):
obj[i] = objectToJson(obj[i])
return obj
else: # 自定义数据类型,将属性转换成字典
# 1. 获取自定义数类属性列表 - 非双下划线开头、非双下划线结尾、非method、非function
fields = [x for x in dir(obj)
if x[:2] != '__'
and x[-2:] != '__'
and 'method' not in str(type(getattr(obj, x)))
and 'function' not in str(type(getattr(obj, x)))]
# 2. 封装成字典
objDict = {}
for field in fields:
objDict[field.replace('_', '')] = objectToJson(getattr(obj, field))
# 3. 将字典返回
return objDict
if className == JsonArray.__name__:
# 只处理 字典、列表、元组、集合以及可转换成上述类型的字符串
if isinstance(value, (list, set, tuple,)): # 列表、元组、集合
return objectToJson(list(value))
elif isinstance(value, dict): # 字典
value = eval('[' + str(value) + ']') # 转换成列表
return objectToJson(value)
elif isinstance(value, str): # 字符串
if value[0:1] == '[' and value[-1:] == ']' and isinstance(eval(value), list):
return objectToJson(eval(value))
elif value[0:1] == '{' and value[-1:] == '}':
value = eval(value)
if isinstance(value, tuple):
return objectToJson(value)
elif isinstance(value, dict):
value = eval('[' + str(value) + ']') # 转换成列表
return objectToJson(value)
if className == JsonObject.__name__:
# 只处理 字典、自定义对象以及可转换成字典的字符串
if isinstance(value, dict):
# 字典
return objectToJson(value)
elif isinstance(value, str) and value[0:1] == '{' and value[-1:] == '}' and isinstance(eval(value), dict):
# 可转换成字典的字符串
return objectToJson(eval(value))
elif not isinstance(value, (dict, str, set, tuple, int, float, bool, complex)):
# 其他自定义类型
return objectToJson(value)
raise JsonParamError('value can not parse to %s:"%s"' % (className, value))
class _JsonTypeUtil:
# todo 优化数据转换
@staticmethod
def caseToInt(value):
return int(value)
@staticmethod
def caseToStr(value):
return str(value)
@staticmethod
def caseToFloat(value):
return float(value)
@staticmethod
def caseToBool(value):
return bool(value)
class CaseTypeError(Exception):
def __init__(self, errorInfo):
super().__init__(self) # 初始化父类
self.errorInfo = errorInfo
def __repr__(self):
return self.errorInfo
def __str__(self):
return self.errorInfo
class JsonParamError(Exception):
def __init__(self, errorInfo):
super().__init__(self)
self.errorInfo = errorInfo
def __repr__(self):
return self.errorInfo
def __str__(self):
return self.errorInfo