Skip to content

Commit 4c230d7

Browse files
committed
Add utility methods to JSONSerializer
1 parent e5ff939 commit 4c230d7

File tree

1 file changed

+21
-2
lines changed

1 file changed

+21
-2
lines changed

src/coherence/serialization.py

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
from __future__ import annotations
66

77
import collections
8+
import json
89
from abc import ABC, abstractmethod
910
from decimal import Decimal
1011
from typing import Any, Callable, Dict, Final, Optional, Type, TypeVar, cast
@@ -70,25 +71,43 @@ def __init__(self) -> None:
7071
self._pickler = JavaProxyPickler()
7172
self._unpickler = JavaProxyUnpickler()
7273

74+
def _to_json_from_object(self, obj: object) -> str:
75+
jsn = jsonpickle.encode(obj, context=self._pickler)
76+
return jsn
77+
7378
def serialize(self, obj: object) -> bytes:
74-
jsn: str = jsonpickle.encode(obj, context=self._pickler)
79+
jsn: str = self._to_json_from_object(obj)
7580
b: bytes = MAGIC_BYTE + jsn.encode()
7681
return b
7782

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+
7887
def deserialize(self, value: bytes) -> T: # type: ignore
7988
if isinstance(value, bytes):
8089
s = value.decode()
8190
if value.__len__() == 0: # empty string
8291
return cast(T, None)
8392
else:
8493
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:])
8695
return r
8796
else:
8897
raise ValueError("Invalid JSON serialization format")
8998
else:
9099
return cast(T, value)
91100

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+
92111

93112
class SerializerRegistry:
94113
_singleton: SerializerRegistry

0 commit comments

Comments
 (0)