Last active
March 24, 2023 18:27
-
-
Save krscott/66bf3e179e051d300952405484d3ed25 to your computer and use it in GitHub Desktop.
This file contains 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 __future__ import annotations | |
from dataclasses import dataclass, asdict, is_dataclass | |
from typing import Any | |
from typing_extensions import dataclass_transform # pip install typing-extensions | |
import dacite # pip install dacite | |
import json | |
@dataclass_transform(kw_only_default=True) | |
class SerdeJson: | |
def __init_subclass__(cls): | |
_ = dataclass(cls) | |
@classmethod | |
def from_dict(cls, data: dict[str, Any]): | |
return dacite.from_dict(cls, data) | |
@classmethod | |
def from_json(cls, data: str): | |
return cls.from_dict(json.loads(data)) | |
def to_dict(self): | |
assert is_dataclass(self) # Suppress type error | |
return asdict(self) | |
def to_json(self): | |
return json.dumps(self.to_dict()) | |
if __name__ == "__main__": | |
class ExampleClass(SerdeJson): | |
name: str | |
age: int | |
is_old: bool | |
def birthday(self): | |
self.age += 1 | |
self.is_old = True | |
a = ExampleClass.from_json(r'{"name": "Kris", "is_old": false, "age": 30}') | |
a.birthday() | |
assert(a.to_json() == r'{"name": "Kris", "age": 31, "is_old": true}') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment