-
Notifications
You must be signed in to change notification settings - Fork 10
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
Deserialize optional fields (Union types) #51
Comments
@ianfiske Hi! Here's a quick solution I can suggest, but just remember to prioritize the types correctly. using Serde
struct B1
y::Float64
end
struct B2
x::Float64
y::Float64
end
struct A
x::Union{B1, B2}
end
function Serde.deser(::Type{<:A}, ::Type{<:Union{B1,B2}}, v)
try
Serde.deser(B2, v)
catch
Serde.deser(B1, v)
end
end
json1 = """
{
"x": {
"x": 1.0,
"y": 2.0
}
}
"""
julia> deser_json(A, json1)
A(B2(1.0, 2.0))
json2 = """
{
"x": {
"y": 2.0
}
}
"""
julia> deser_json(A, json2)
A(B1(2.0)) |
If you provide me with more real-world cases, or suggest the expected interface, we can consider how to support this within the library. |
Take a look at this #37 (comment), it might be relevant to you. |
Thank you for the suggestion @gryumov ! That seems like it should work. Here's an example that more closely resembles my use-case. There are a number of data sources. Each data source (timeseries) can either be an
|
Accidentally "closed" there... thought it was a drop-down option along with the main button. |
I think this feature is easy to implement, just select the type that best matches the field when deserializing |
Commenting to also note my interest. In addition to the above use cases, I also have some fields as |
I am trying to deserialize user config data that has fields with multiple possible option types, as implemented with a type-union. This seems to not be supported. Are there plans to support this? Or any alternatives you might suggest?
Here's an example:
gives the error
The text was updated successfully, but these errors were encountered: