-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJSON_Encoder_Decoder.py
More file actions
71 lines (56 loc) · 1.93 KB
/
Copy pathJSON_Encoder_Decoder.py
File metadata and controls
71 lines (56 loc) · 1.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
'''
JSONEncode / JSONDecoder : useful to serialize any kind of object
'''
import json
class Vector:
def __init__(self, *args):
self.args = args
def __str__(self):
return f'{self.__dict__}'
class Encoder(json.JSONEncoder):
def default(self, v):
if isinstance(v, Vector):
return v.__dict__
else:
return super().default(self, v)
class Decoder(json.JSONDecoder):
def __init__(self):
super().__init__(object_hook=self.decode_vector)
def decode_vector(self, d):
return Vector(*d["args"]) # Si on ne passe une liste non définie d'arguments
class Vector2:
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def __str__(self):
return f'{self.__dict__}'
class Encoder(json.JSONEncoder):
def default(self, v):
if isinstance(v, Vector2):
return v.__dict__
else:
return super().default(self, v)
class Decoder(json.JSONDecoder):
def __init__(self):
super().__init__(object_hook=self.decode_vector)
def decode_vector(self, d):
return Vector2(**d) # Si on ne passe une liste finie d'arguments positionnels
v1 = Vector(4, 2, 6)
print( v1, type(v1) )
json_str = json.dumps(v1, cls=Vector.Encoder)
print( json_str )
v1_back = json.loads(json_str, cls=Vector.Decoder)
print( v1_back, type(v1_back) )
json_str2 = json.dumps(json.loads(json_str, cls=Vector.Decoder), cls=Vector.Encoder)
print( json_str2 )
print()
v2 = Vector2(4, 2, 6)
print( v2, type(v2) )
json_str3 = json.dumps(v2, cls=Vector2.Encoder)
print( json_str3, type(json_str3) )
v2_back = json.loads(json_str3, cls=Vector2.Decoder)
print( v2_back, type(v2_back) )
json_str4 = json.dumps(json.loads(json_str3, cls=Vector2.Decoder), cls=Vector2.Encoder)
print( json_str4, type(json_str4) )
print()