codekingpro/portable-devtools
114k
1from abc import abstractmethod
2from typing import Any, Dict, Generic, Protocol, TypeVar
3from typing_extensions import Self
4import json
5
6T = TypeVar("T", covariant=True)
7
8
9class JSONSerializable(Protocol[T]):
10 """A generic interface for objects that can be serialized to JSON"""
11
12 def to_json_str(self) -> str:
13 """Serializes the object to JSON"""
14 ...
15
16 @classmethod
17 def from_json_str(cls, json_str: str) -> Self:
18 """Deserializes the object from JSON"""
19 ...
20
21 def to_json(self) -> Dict[str, Any]:
22 """Serializes the object to a JSON compatible dictionary"""
23 ...
24
25 @classmethod
26 def from_json(cls, json_map: Dict[str, Any]) -> Self:
27 """Deserializes the object from JSON"""
28 ...
29
30
31class BaseModelJSONSerializable(Generic[T]):
32 """A mixin for BaseModels that allows a class to be serialized to JSON"""
33
34 def to_json_str(self) -> str:
35 """Serializes the object to JSON"""
36 return self.model_dump_json()
37
38 def to_json(self) -> Dict[str, Any]:
39 """Serializes the object to a JSON compatible dictionary"""
40 return json.loads(self.model_dump_json()) # type: ignore[no-any-return]
41
42 @abstractmethod
43 def model_dump_json(self) -> str:
44 """Abstract method that should be implemented to dump the model to JSON"""
45 pass
46
47 @classmethod
48 @abstractmethod
49 def from_json(cls, json_map: Dict[str, Any]) -> T:
50 """Deserializes the object from JSON"""
51 pass
52 