繁体   English   中英

带有嵌套自定义类型的python(内置)json de / serilazation

[英]python (built-in)json de/serilazation with nested custom types

我对python2(2.7)中的json模块没有太多经验。 现在,我面临一个问题:如何将自定义对象序列化为json,然后反序列化它。

我以这个对象层次结构为例:

class Company(object):
    def __init__(self, company_id):
        self.company_id = company_id
        self.name = ''
        # other 10 attributes with simple type
        ...
        self.departments = [] #list of Dept objects

class Dept(object):
    def __init__(self, dept_id):
        self.dept_id = dept_id
        self.name = ''
        # other 10 attributes with simple type
        ...
        self.persons = [] #list of Person objs


class Person(object):
    def __init__(self, per_id):
        self.per_id = per_id
        self.name = ''
        # other 10 attributes with simple type
        ...
        self.skills = [] #list of Skill objs

class Skill(object):
    def __init__(self, skill_id):
        self.skill_id = skill_id
        self.name = ''
        # other 10 attributes with simple type
        ...
        self.foos = [] #list of Foo objs

class Foo(object):
    .....

现在说我从Company获得了一个对象,并填充了嵌套对象的所有属性和列表。 我想将对象保存到json文件中。 然后将其加载回去,以使那些嵌套对象( departments, persons, skills )也被加载。

我读过pydoc,知道json de / encoding是基于dict的。 我现在可以使用以下方法进行序列化:

    json.dump(company_obj, jsonfile, default = lambda o: o.__dict__, sort_keys=True, indent=4)

但是稍后很难将其退还给Company

我以为这个问题很普遍。 我在SO和google上进行了搜索,但没有找到有用的信息。

在这种情况下,执行json序列化和反序列化的正确方法是什么?

您需要的是自定义编码器和解码器。 这些内容记录在这里: http : //docs.python.org/2/library/json.html#encoders-and-decoders

一个可行的解决方案是在编码时将合格的类名添加到dict,并在解码时使用它来创建正确的类的实例。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM