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 dynamic deserialization of AbstractTypes #79

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

gryumov
Copy link
Member

@gryumov gryumov commented Feb 12, 2025

Pull request checklist

  • Did you bump the project version?
  • Did you add a description to the Pull Request?
  • Did you add new tests?
  • Did you add reviewers?
using Serde

abstract type AbstractFoo end

struct Foo1 <: AbstractFoo
    name::String
    num::Int64
end

struct Foo2 <: AbstractFoo
    name::String
    str::String
end

Serde.ClassType(::Type{AbstractFoo}) = Serde.AbstractType()

#___

Serde.subtype_key(::Type{AbstractFoo}) = :name
Serde.subtypes(::Type{AbstractFoo}) = InteractiveUtils.subtypes(AbstractFoo)

#___

h1 = " {\"name\": \"Foo1\" ,\"num\":100}      "
h2 = " {\"name\": \"Foo2\" ,\"str\":\"test\"} "
h3 = " {\"name\": \"Foo2\" ,\"str\":\"test\"} "
h4 = " {\"name\": \"Foo2\" ,\"num\":100}      "

julia> deser_json(AbstractFoo, h1)
Foo1("Foo1", 100)

julia> deser_json(AbstractFoo, h2)
Foo2("Foo2", "test")

julia> @time deser_json(AbstractFoo, h1)
  0.010999 seconds (1.28 k allocations: 1.197 MiB)
Foo1("Foo1", 100)

julia> @time deser_json(Foo1, h1)
  0.000033 seconds (14 allocations: 824 bytes)
Foo1("Foo1", 100)

julia> @time InteractiveUtils.subtypes(AbstractFoo)
  0.013692 seconds (1.26 k allocations: 1.196 MiB)
2-element Vector{Any}:
 Foo1
 Foo2

Serde.subtypes(::Type{AbstractFoo}) = (Foo1, Foo2)

julia> @time deser_json(AbstractFoo, h1)
  0.000050 seconds (14 allocations: 816 bytes)
Foo1("Foo1", 100)

julia> @time deser_json(AbstractFoo, h2)
  0.000041 seconds (16 allocations: 864 bytes)
Foo2("Foo2", "test")

@gryumov gryumov force-pushed the feature/dynamic-subtype-deserialization branch from fc1362c to d1f9ad0 Compare February 12, 2025 15:05
Copy link

📘 A preview of the documentation will be here soon

@gryumov gryumov force-pushed the feature/dynamic-subtype-deserialization branch from d1f9ad0 to 0aac2fe Compare February 12, 2025 15:25
@gryumov gryumov force-pushed the feature/dynamic-subtype-deserialization branch from 0aac2fe to 186d12d Compare February 12, 2025 15:31
@gryumov gryumov linked an issue Feb 12, 2025 that may be closed by this pull request
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.

Deserialization of abstract types having multiple concrete subtypes
1 participant