Created
December 29, 2022 23:29
-
-
Save brettvitaz/9e661f903143f2de06c6eaafdec2588b to your computer and use it in GitHub Desktop.
JsonSerializable
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from abc import ABC | |
class JsonSerializable(ABC): | |
IGNORE = [] | |
@staticmethod | |
def serialize(obj): | |
if isinstance(obj, JsonSerializable): | |
return obj.to_json() | |
return obj | |
@staticmethod | |
def deserialize(json_mapping: dict): | |
def deserialize_inner(obj: dict): | |
ret = dict() | |
for k, v in obj.items(): | |
if k in json_mapping: | |
v = json_mapping.get(k).from_json(v) | |
ret[k] = v | |
return ret | |
return deserialize_inner | |
def to_json(self): | |
ret = {} | |
for k, v in self.__dict__.items(): | |
if k not in self.IGNORE: | |
ret[k] = v | |
return ret | |
@classmethod | |
def from_json(cls, kwargs): | |
return cls(**kwargs) if kwargs is not None else None | |
def __repr__(self): | |
return f"{self.__class__.__name__}({self.to_json()})" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment