lidatong / dataclasses-json

Easily serialize Data Classes to and from JSON
MIT License
1.34k stars 151 forks source link

[FEATURE] V1 - Class Hierarchy SerDe #456

Open george-zubrienko opened 11 months ago

george-zubrienko commented 11 months ago

Description

V1 should support out of box code like this:

from dataclasses_json.api import from_json, to_json

@dataclass
class A:
    who_am_i = "A"
    a: int

@dataclass
class B(A):
    who_am_i = "B"
    b: Optional[int]

@dataclass
class C(A):
    who_am_i = "C"
    c: Optional[int]
    d: Optional[A]

dataclasses_json\
  .register(JsonSerializer[A]())\
  .register(JsonSerializer[B]())\
  .register(JsonSerializer[C]())

to_json(A(a=1)) # '{"who_am_i": "A", "a": 1}'

to_json(B(a=1, b=2)) # '{"who_am_i": "B", "a": 1, "b": 2}'
to_json(B(a=1, b=2), A) # '{"who_am_i": "B", "a": 1}'

to_json(C(a=1, c=2, d=A(a=2))) # '{"who_am_i": "C", "a": 1, "c": 1, "d": { "a": 2 } }'
to_json(C(a=1, c=2, d=A(a=2)), A) # '{"who_am_i": "C", "a": 1}'

x = from_json('{"who_am_i": "A", "a": 1}', A) # x: A
x.a # 1
x.who_am_i # 'A'

x = from_json('{"a": 1}', A) # x: A
x.a # 1
x.who_am_i # 'A'

x = from_json('{"who_am_i": "A", "a": null}', A) # Error when deserializing from json string to type A: field A.a does not allow null values

x = from_json( '{"who_am_i": "B", "a": 1, "b": 2}', B) # x: B
x = from_json( '{"a": 1, "b": 2}', B) # x: B
x.who_am_i # 'B'

x = from_json( '{"a": 1}', B) # x: B
x.b # None
x.a # 1
x.who_am_i # 'B'

Possible solution

No response

Alternatives

N/A

Context

No response