def object_from_json(self, object_type, object_json): """ Given a blob of JSON representing a Zenpy object, recursively deserialize it and any nested objects it contains. This method also adds the deserialized object to the relevant cache if applicable. """ if not isinstance(object_json, dict): return object_json ZenpyClass = self.class_for_type(object_type) obj = ZenpyClass(api=self.api) for key, value in object_json.items(): if isinstance(value, dict): key = self.format_key(key, parent=obj) if key in self.class_mapping: value = self.object_from_json(key, value) elif as_singular(key) in self.class_mapping: value = self.object_from_json(as_singular(key), value) elif isinstance(value, list) and self.format_key(as_singular(key), parent=obj) in self.class_mapping: zenpy_objects = list() for item in value: zenpy_objects.append(self.object_from_json(self.format_key(as_singular(key), parent=obj), item)) value = zenpy_objects setattr(obj, key, value) add_to_cache(obj) return obj
def _deserialize(self, key, obj, value): if isinstance(value, dict): key = self.format_key(key, parent=obj) if key in self.class_mapping: value = self.object_from_json(key, value, parent=obj) elif as_singular(key) in self.class_mapping: value = self.object_from_json(as_singular(key), value, parent=obj) elif isinstance(value, list) and self.format_key(as_singular(key), parent=obj) in self.class_mapping: zenpy_objects = list() for item in value: object_type = self.format_key(as_singular(key), parent=obj) zenpy_objects.append(self.object_from_json(object_type, item, parent=obj)) value = zenpy_objects return key, value
def deserialize(self, response_json): """ Locate and deserialize all objects in the returned JSON. Return a dict keyed by object_type. If the key is plural, the value will be a list, if it is singular, the value will be an object of that type. :param response_json: """ response_objects = dict() if all((t in response_json for t in ('ticket', 'audit'))): response_objects[ "ticket_audit"] = self.object_mapping.object_from_json( "ticket_audit", response_json) # Locate and store the single objects. for zenpy_object_name in self.object_mapping.class_mapping: if zenpy_object_name in response_json: zenpy_object = self.object_mapping.object_from_json( zenpy_object_name, response_json[zenpy_object_name]) response_objects[zenpy_object_name] = zenpy_object # Locate and store the collections of objects. for key, value in response_json.items(): if isinstance(value, list): zenpy_object_name = as_singular(key) if zenpy_object_name in self.object_mapping.class_mapping: response_objects[key] = [] for object_json in response_json[key]: zenpy_object = self.object_mapping.object_from_json( zenpy_object_name, object_json) response_objects[key].append(zenpy_object) return response_objects