Unmarshalling to a Julia type when type has Union in the Attribute values?

Hi,
I am trying to unmarshal a json to a Struct type where there is Union in type attributes but it does not work. Is there a way to do that?

That exercise works:

using Unmarshal

input = "{ \"id\": 25073877, \"id_str\": \"25073877\"}"

struct UserX
    id::Int64
    id_str::String
end

Unmarshal.unmarshal(UserX, JSON.parse(input))

But Having Union in the struct Marshalling is not working:

struct UserY
    id::Union{Int64, Nothing}
    id_str::Union{String, Nothing}
end

Unmarshal.unmarshal(UserY, JSON.parse(input))

It through the following error:

ERROR: MethodError: unmarshal(::Type{Union{Nothing, String}}, ::String, ::Bool, ::Int64) is ambiguous. Candidates:
  unmarshal(DT::Type, parsedJson::String, verbose::Bool, verboseLvl::Int64) in Unmarshal at /home/datapsycho/.julia/packages/Unmarshal/G72dP/src/Unmarshal.jl:38
  unmarshal(::Type{Union{Nothing, T}}, x, verbose::Bool, verboseLvl::Int64) where T in Unmarshal at /home/datapsycho/.julia/packages/Unmarshal/G72dP/src/Unmarshal.jl:232
Possible fix, define
  unmarshal(::Type{Union{Nothing, T}}, ::String, ::Bool, ::Int64) where T

Is there any other way I can do marshal?

1 Like

Defining the function as proposed is doing what you want:

julia> import Unmarshal.unmarshal

julia> unmarshal(::Type{Union{T,Nothing}}, x :: String, verbose :: Bool = false, verboseLvl :: Int = 0) where T = unmarshal(T, x, verbose, verboseLvl)
unmarshal (generic function with 69 methods)

julia> Unmarshal.unmarshal(UserY, JSON.parse(input))
UserY(25073877, "25073877")

But I think that this would be worth opening an issue at… I see, you already did:
https://github.com/lwabeke/Unmarshal.jl/issues/31

Well done.

2 Likes