diff --git a/libremsonic/server/api_objects.py b/libremsonic/server/api_objects.py index 303a298..b22dbbf 100644 --- a/libremsonic/server/api_objects.py +++ b/libremsonic/server/api_objects.py @@ -4,49 +4,50 @@ from datetime import datetime from dateutil import parser +def _from_json(cls, data): + """ + Approach for deserialization here: + https://stackoverflow.com/a/40639688/2319844 + """ + print(cls, data) + annotations: Dict[str, Any] = getattr(cls, '__annotations__', {}) + + # Handle lists of objects. + if cls == str: + return data + if issubclass(cls, List): + list_type = cls.__args__[0] + instance: List[list_type] = list() + for value in data: + instance.append(_from_json(list_type, value)) + + # Handle dictionaries of objects. + elif issubclass(cls, Dict): + key_type, val_type = cls.__args__ + instance: Dict[key_type, val_type] = dict() + for key, value in data.items(): + instance.update(_from_json(key_type, key), + _from_json(val_type, value)) + + # Handle everything else by first instantiating the class, then adding + # all of the sub-elements, recursively calling from_json on them. + else: + instance: cls = cls() + for name, value in data.items(): + field_type = annotations.get(name) + print('ohea', field_type, value) + if inspect.isclass(field_type): + setattr(instance, name, _from_json(field_type, value)) + else: + setattr(instance, name, value) + + return instance + + class APIObject: @classmethod def from_json(cls, data): - """ - Approach for deserialization here: - https://stackoverflow.com/a/40639688/2319844 - """ - annotations: Dict[str, Any] = getattr(cls, '__annotations__', {}) - - # Handle lists of objects. - if issubclass(cls, List): - list_type = cls.__args__[0] - instance: List[list_type] = list() - for value in data: - instance.append(list_type.from_json(value)) - - # Handle dictionaries of objects. - elif issubclass(cls, Dict): - key_type = cls.__args__[0] - val_type = cls.__args__[1] - instance: Dict[key_type, val_type] = dict() - for key, value in data.items(): - instance.update(key_type.from_json(key), - key_type.from_json(value)) - - # Handle everything else by first instantiating the class, then adding - # all of the sub-elements, recursively calling from_json on them. - else: - instance: cls = cls() - for name, value in data.items(): - field_type = annotations.get(name) - print('ohea', field_type, value) - if inspect.isclass(field_type): - if isinstance(value, (dict, tuple, list, set, frozenset)): - setattr(instance, name, field_type.from_json(value)) - elif field_type == datetime: - setattr(instance, name, parser.parse(value)) - else: - setattr(instance, name, value) - else: - setattr(instance, name, value) - - return instance + return _from_json(cls, data) def get(self, field, default=None): return getattr(self, field, default)