Type HierarchyΒΆ

If you have a hierarchy of types and you want to be able to deserialize them using base type, you need to register your base type with type_field() decorator. First argument is a name of class field, where you will put aliases for child types.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
from pyjackson import deserialize, serialize
from pyjackson.decorators import type_field


@type_field('type_alias')
class Parent:
    type_alias = 'parent'  # also could be None for abstract parents


class Child1(Parent):
    type_alias = 'child1'

    def __init__(self, a: int):
        self.a = a


class Child2(Parent):
    type_alias = 'child2'

    def __init__(self, b: str):
        self.b = b


serialize(Child1(1), Parent)  # {'type_alias': 'child1', 'a': 1}
deserialize({'type_alias': 'child2', 'b': 'b'}, Parent)  # Child2('b')