Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Jackson style subtype parsing #84

Closed
wants to merge 1 commit into from
Closed

Add Jackson style subtype parsing #84

wants to merge 1 commit into from

Conversation

crutcher
Copy link

    Declaring a base class which can delegeate from_json()
    to registered subclasses:
    >>> @dataclass_json(parse_as_subtype=True)
    >>> @dataclass(frozen=True)
    >>> class Base:
    >>>     x: int
    >>> 
    >>> @dataclass_json(register_subtype_of=Base)
    >>> @dataclass(frozen=True)
    >>> class Foo(Base):
    >>>     y: str
    >>> 
    >>> b = Base(1)
    >>> foo = Foo(2, 'abc')
    >>>
    >>> b.to_json()  # '{"x": 1}'
    >>> foo.to_json()  # '{"x": 2, "y": "abc", "@type": "Foo"}'
    >>>
    >>> Base.from_json('{"x": 3}') # Base(3)
    >>> Base.from_json('{"x": 2, "y": "abc", "@type": "Foo"}') # Foo(2, "abc")

@crutcher
Copy link
Author

Hi; was looking for the subtype mechanism from java's Jackson library, and added it to dataclasses_json.

I'm not sure how to approach this for you; and it doesn't play cleanly with mm (since mm doesn't do this).

@george-zubrienko
Copy link
Collaborator

I think it should be enough to inherit Base from the DataClassJsonMixin to have this more or less solved automatically?

@george-zubrienko
Copy link
Collaborator

Closing in favour of #442 - can use for units though

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants