1
- from dataclasses import dataclass , field
2
- from dataclasses_json import dataclass_json , config
3
- from typing import Optional , Iterable
4
1
import sys
5
- import json
2
+ from typing import Literal , Union , Tuple
3
+ from pydantic import BaseModel , RootModel
6
4
7
5
8
- # TODO tkulik: try to get rid of the `dataclasses_json` dependency
6
+ class SomeEnum (RootModel ):
7
+ class Field1 (RootModel [Literal ['Field1' ]]):
8
+ pass
9
9
10
+ class Field2 (BaseModel ):
11
+ Field2 : Tuple [int , int ]
10
12
11
- enum_field = lambda : field (default = None , metadata = config (exclude = lambda x : x is None ))
13
+ class Field3 (BaseModel ):
14
+ class __InnerStruct (BaseModel ):
15
+ a : str
16
+ b : int
17
+ Field3 : __InnerStruct
12
18
13
- @dataclass_json
14
- @dataclass
15
- class SomeEnum :
16
- class VariantIndicator :
17
- pass
19
+ class Field4 (BaseModel ):
20
+ Field4 : 'SomeEnum'
18
21
19
- class Field3Type :
20
- a : str
21
- b : int
22
-
23
- class Field5Type :
24
- a : Iterable ['SomeEnum' ]
25
-
26
- Field1 : Optional [VariantIndicator ] = enum_field ()
27
- Field2 : Optional [tuple [int , int ]] = enum_field ()
28
- Field3 : Optional [Field3Type ] = enum_field ()
29
- Field4 : Optional [Iterable ['SomeEnum' ]] = enum_field ()
30
- Field5 : Optional [Field5Type ] = enum_field ()
31
-
32
- def deserialize (json ):
33
- if not ":" in json :
34
- if json == '"Field1"' :
35
- return SomeEnum (Field1 = SomeEnum .VariantIndicator ())
36
- else :
37
- raise Exception (f"Deserialization error, undefined variant: { json } " )
38
- else :
39
- return SomeEnum .from_json (json )
40
-
41
- def serialize (self ):
42
- if self .Field1 is not None :
43
- return '"Field1"'
44
- else :
45
- return SomeEnum .to_json (self )
46
-
47
- @dataclass_json
48
- @dataclass
49
- class UnitStructure :
50
- def deserialize (json ):
51
- if json == "null" :
52
- return UnitStructure ()
53
- else :
54
- Exception (f"Deserialization error, undefined value: { json } " )
55
-
56
- def serialize (self ):
57
- return 'null'
58
-
59
- @dataclass_json
60
- @dataclass
61
- class TupleStructure :
62
- Tuple : tuple [int , str , int ]
63
-
64
- def deserialize (json ):
65
- return TupleStructure .from_json (f'{{ "Tuple": { json } }}' )
66
-
67
- def serialize (self ):
68
- return json .dumps (self .Tuple )
69
-
70
- @dataclass_json
71
- @dataclass
72
- class NamedStructure :
22
+ class Field5 (BaseModel ):
23
+ class __InnerStruct (BaseModel ):
24
+ a : 'SomeEnum'
25
+ Field5 : __InnerStruct
26
+
27
+ root : Union [Field1 , Field2 , Field3 , Field4 , Field5 ]
28
+
29
+
30
+ class UnitStructure (RootModel ):
31
+ root : None
32
+
33
+
34
+ class TupleStructure (RootModel ):
35
+ root : Tuple [int , str , int ]
36
+
37
+
38
+ class NamedStructure (BaseModel ):
73
39
a : str
74
40
b : int
75
- c : Iterable ['SomeEnum' ]
41
+ c : SomeEnum
42
+
76
43
77
- def deserialize (json ):
78
- return NamedStructure .from_json (json )
79
-
80
- def serialize (self ):
81
- return self .to_json ()
82
44
83
45
###
84
46
### TESTS:
@@ -88,32 +50,36 @@ def serialize(self):
88
50
input = input .rstrip ()
89
51
try :
90
52
if index < 5 :
91
- deserialized = SomeEnum .deserialize (input )
53
+ deserialized = SomeEnum .model_validate_json (input )
92
54
elif index == 5 :
93
- deserialized = UnitStructure .deserialize (input )
55
+ deserialized = UnitStructure .model_validate_json (input )
94
56
elif index == 6 :
95
- deserialized = TupleStructure .deserialize (input )
57
+ deserialized = TupleStructure .model_validate_json (input )
96
58
else :
97
- deserialized = NamedStructure .deserialize (input )
59
+ deserialized = NamedStructure .model_validate_json (input )
98
60
except :
99
61
raise (Exception (f"This json can't be deserialized: { input } " ))
100
- serialized = deserialized .serialize ()
62
+ serialized = deserialized .model_dump_json ()
101
63
print (serialized )
102
64
103
65
104
66
# def handle_msg(json):
105
- # a = SomeEnum.deserialize (json)
106
- # if a.Field1 is not None :
67
+ # a = SomeEnum.model_validate_json (json)
68
+ # if isinstance(a.root, SomeEnum.Field1) :
107
69
# print("SomeEnum::Field1")
108
- # elif a.Field2 is not None :
109
- # print(a.Field2[0])
110
- # print(a.Field2[1])
111
- # elif a.Field3 is not None :
112
- # print(a.Field3)
113
- # elif a.Field4 is not None :
114
- # print(a.Field4)
115
- # elif a.Field5 is not None :
116
- # print(a.Field5)
70
+ # elif isinstance(a.root, SomeEnum.Field2) :
71
+ # print(a.root. Field2[0])
72
+ # print(a.root. Field2[1])
73
+ # elif isinstance(a.root, SomeEnum.Field3) :
74
+ # print(a.root. Field3)
75
+ # elif isinstance(a.root, SomeEnum.Field4) :
76
+ # print(a.root. Field4)
77
+ # elif isinstance(a.root, SomeEnum.Field5) :
78
+ # print(a.root. Field5)
117
79
118
80
# handle_msg('"Field1"')
119
- # handle_msg('{"Field2": [10, 12]}')
81
+ # handle_msg('{"Field2": [10, 12]}')
82
+ # handle_msg('{"Field3": { "a": "10", "b": 12 } }')
83
+ # handle_msg('{"Field4": { "Field4": "Field1" } }')
84
+ # handle_msg('{"Field5": { "a": "Field1" } }')
85
+ # handle_msg('{"Field5": { "a": { "Field5": { "a": "Field1" } } } }')
0 commit comments