我创建了一个包含字符串键和一些类作为值的字典。现在,我想使用json对其进行序列化和反序列化。
class A:
def __init__(self, val):
self.val = val
class B(A):
def __init__(self, val, additional_val):
super(B, self).__init__(val)
self.additional_val= additional_val
class C(B):
def __init__(self, val, additional_val, enabled):
super(C, self).__init__(val, additional_val)
self.enabled = enabled
my_dict = {'0': A(0), '1': B(5, 6), '2': C(7,8,True)}
现在我要序列化它。我发现用jsons进行序列化的最简单方法(使用python 3.6)。但是如何将它反序列化回原始对象呢?我发现的所有示例都是针对非常简单的对象(str,dict,list)的。
尝试这个:
import json
def convert_to_dict(obj):
"""
A function takes in a custom object and returns a dictionary representation of the object.
This dict representation includes meta data such as the object's module and class names.
"""
# Populate the dictionary with object meta data
obj_dict = {
"__class__": obj.__class__.__name__,
"__module__": obj.__module__
}
# Populate the dictionary with object properties
obj_dict.update(obj.__dict__)
return obj_dict
my_dict = {'0': A(0), '1': B(5, 6), '2': C(7,8,True)}
mydict_dump = json.dumps(my_dict, default=convert_to_dict, indent=4, sort_keys=True)
final_result = json.loads(mydict_dump)
print(final_result)
您可以参考这篇中等文章以了解更多信息:
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句