@@ -19,8 +19,7 @@ def recast_object(
1919 return
2020 for k , v in json_data .items ():
2121 if isinstance (v , dict ):
22- child_cls = _field_to_type (cls .__dataclass_fields__ [k ].type , k , classes )
23- recast_object (child_cls , v , classes )
22+ _recast_nested_dict (cls , json_data , k , v , classes )
2423 elif isinstance (v , list ):
2524 json_data [k ] = _recast_lists (cls , k , v , classes )
2625 elif isinstance (v , set ):
@@ -34,6 +33,37 @@ def recast_object(
3433 raise InvalidRequest (f"Unsupported type: { type (v )} for { k } " )
3534
3635
36+ def _recast_nested_dict (
37+ cls : Any ,
38+ json_data : Mapping [str , Any ],
39+ k : str ,
40+ v : Dict [str , Any ],
41+ classes : Dict [str , Any ],
42+ ) -> None :
43+ """
44+ Attempts to recursively cast the dict elements.
45+ On KeyError, we know that the "parent" property ,
46+ does not have a specific class to be casted to.
47+ Therefore we figure out what the "nested object" class might be,
48+ recursively cast those,
49+ to finally assign to the "parent" dict the right class
50+
51+ :param Any cls:
52+ :param Mapping json_data:
53+ :param str k:
54+ :param Any v:
55+ :param dict classes:
56+ """
57+ try :
58+ child_cls = _field_to_type (cls .__dataclass_fields__ [k ].type , k , classes )
59+ recast_object (child_cls , v , classes )
60+ except KeyError :
61+ child_cls = _field_to_type (cls .__dataclass_fields__ [k ].type , k , classes )
62+ for _child , _child_definition in v .items ():
63+ recast_object (child_cls , _child_definition , classes )
64+ json_data [k ][_child ] = _child_definition
65+
66+
3767def _recast_lists (cls : Any , k : str , v : List [Any ], classes : Dict [str , Any ]) -> List [Any ]:
3868 # Leave as is if type is Any
3969 if cls is typing .Any :
0 commit comments