|
5 | 5 | from __future__ import annotations
|
6 | 6 |
|
7 | 7 | import collections
|
| 8 | +import json |
8 | 9 | from abc import ABC, abstractmethod
|
9 | 10 | from decimal import Decimal
|
10 | 11 | from typing import Any, Callable, Dict, Final, Optional, Type, TypeVar, cast
|
@@ -70,25 +71,43 @@ def __init__(self) -> None:
|
70 | 71 | self._pickler = JavaProxyPickler()
|
71 | 72 | self._unpickler = JavaProxyUnpickler()
|
72 | 73 |
|
| 74 | + def _to_json_from_object(self, obj: object) -> str: |
| 75 | + jsn = jsonpickle.encode(obj, context=self._pickler) |
| 76 | + return jsn |
| 77 | + |
73 | 78 | def serialize(self, obj: object) -> bytes:
|
74 |
| - jsn: str = jsonpickle.encode(obj, context=self._pickler) |
| 79 | + jsn: str = self._to_json_from_object(obj) |
75 | 80 | b: bytes = MAGIC_BYTE + jsn.encode()
|
76 | 81 | return b
|
77 | 82 |
|
| 83 | + def _to_object_from_json(self, json_str: str) -> T: # type: ignore |
| 84 | + o = jsonpickle.decode(json_str, context=self._unpickler) |
| 85 | + return o |
| 86 | + |
78 | 87 | def deserialize(self, value: bytes) -> T: # type: ignore
|
79 | 88 | if isinstance(value, bytes):
|
80 | 89 | s = value.decode()
|
81 | 90 | if value.__len__() == 0: # empty string
|
82 | 91 | return cast(T, None)
|
83 | 92 | else:
|
84 | 93 | if ord(s[0]) == ord(MAGIC_BYTE):
|
85 |
| - r = jsonpickle.decode(s[1:], context=self._unpickler) |
| 94 | + r: T = self._to_object_from_json(s[1:]) |
86 | 95 | return r
|
87 | 96 | else:
|
88 | 97 | raise ValueError("Invalid JSON serialization format")
|
89 | 98 | else:
|
90 | 99 | return cast(T, value)
|
91 | 100 |
|
| 101 | + def flatten_to_dict(self, o: object) -> dict[Any, Any]: |
| 102 | + jsn = self._to_json_from_object(o) |
| 103 | + d = json.loads(jsn) |
| 104 | + return d |
| 105 | + |
| 106 | + def restore_to_object(self, the_dict: dict[Any, Any]) -> T: # type: ignore |
| 107 | + jsn = json.dumps(the_dict) |
| 108 | + o: T = self._to_object_from_json(jsn) |
| 109 | + return o |
| 110 | + |
92 | 111 |
|
93 | 112 | class SerializerRegistry:
|
94 | 113 | _singleton: SerializerRegistry
|
|
0 commit comments