Open ianfiske opened 4 months ago
@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 https://github.com/bhftbootcamp/Serde.jl/issues/37#issuecomment-2091038501, 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 Int
(correspondong to some id in a db) or a structure that describes how to locate the file locally.
struct LocalFileData
file_path::String
column_name::String
end
struct Data
timeseries1::Union{LocalFileData,Int}
timeseries2::Union{LocalFileData,Int}
end
json = """
{
"timeseries1": 13235,
"timeseries2": {
"file_path": "/path/to/csv"
"column_name": "A"
}
}
"""
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 Union{Int, Nothing}
as an example.
Works really well in JSON3.jl. But would be nice to have a multiformat de/serialiser like Serde.jl
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