import json
serializableClassDictionary = {}
def registerClass(sourceClass):
serializableClassDictionary[sourceClass.__name__] = sourceClass
class RegisteredSerializableMeta(type):
def __new__(metaClass, className, baseClassTuple, classMemberDictionary):
classInstance = type.__new__(metaClass, className, baseClassTuple, classMemberDictionary)
registerClass(classInstance)
return classInstance
class Serializable:
def __init__(self, *argumentTuple):
self.argumentTuple = argumentTuple
def serialize(self):
return json.dumps(
{
"className" : self.__class__.__name__,
"argumentTuple" : self.argumentTuple,
}
)
class RegisteredSerializable(Serializable, metaclass = RegisteredSerializableMeta):
pass
def deserialize(jsonString):
jsonDictionary = json.loads(jsonString)
className = jsonDictionary["className"]
targetClassName = serializableClassDictionary[className]
return targetClassName(*jsonDictionary["argumentTuple"])
class Vector3D(RegisteredSerializable):
def __init__(self, x, y, z):
super().__init__(x, y, z)
self.x, self.y, self.z = x, y, z
vector = Vector3D(10, -7, 3)
jsonString = vector.serialize()
print("기존 : ", vector )
print("직렬화 : ", jsonString )
print("역직렬화 : ", deserialize(jsonString))
"""
기존 : <__main__.Vector3D object at 0x7fab3278fb80>
직렬화 : {"className": "Vector3D", "argumentTuple": [10, -7, 3]}
역직렬화 : <__main__.Vector3D object at 0x7fab325d9930>
"""