From 1e15159758e02a7d6d2c886d14beefed343c42b6 Mon Sep 17 00:00:00 2001 From: Liza <90000517+eliza-eliza@users.noreply.github.com> Date: Fri, 16 Aug 2024 00:22:47 +0300 Subject: [PATCH] Add Tuple deserialization (#60) Co-authored-by: Elizaveta Gryumova Co-authored-by: Stanislav Gryumov <33372067+gryumov@users.noreply.github.com> --- Project.toml | 2 +- src/De/Deser.jl | 12 ++++++++++++ test/deser.jl | 41 +++++++++++++++++++++++++++++++++++++++++ 3 files changed, 54 insertions(+), 1 deletion(-) diff --git a/Project.toml b/Project.toml index 75f1d92b..61711959 100644 --- a/Project.toml +++ b/Project.toml @@ -1,6 +1,6 @@ name = "Serde" uuid = "db9b398d-9517-45f8-9a95-92af99003e0e" -version = "3.2.0" +version = "3.3.0" [deps] CSV = "336ed68f-0bac-5ca0-87d4-7b16caf5d00b" diff --git a/src/De/Deser.jl b/src/De/Deser.jl index c40fc061..18c48bc3 100644 --- a/src/De/Deser.jl +++ b/src/De/Deser.jl @@ -320,6 +320,18 @@ function deser( return map(x -> deser(eltype(T), x), data) end +function deser( + ::ArrayType, + ::Type{T}, + x::D, +)::T where {T<:Tuple,D<:Union{Tuple,AbstractVector}} + if (T === Tuple) || isa(T, UnionAll) + T(x) + else + T(deser(t, v) for (t, v) in zip(fieldtypes(T), x)) + end +end + """ Serde.custom_name(::Type{T}, ::Val{x}) -> x diff --git a/test/deser.jl b/test/deser.jl index e8eac194..a22b3e71 100644 --- a/test/deser.jl +++ b/test/deser.jl @@ -682,4 +682,45 @@ using Test, Dates @test Serde.deser(WithMissing, Dict("y" => 3, "x" => nothing)) == WithMissing(3, missing) @test Serde.deser(WithMissing, Dict("y" => 4, "x" => missing)) == WithMissing(4, missing) end + + @testset "Case №39: Deserialization Tuple" begin + struct DifferentTuples + a::Tuple + b::NTuple{2} + c::Tuple{String,String,String} + d::Tuple{String,Int64} + e::Tuple{Float64,Int64} + end + + exp_str = """ + { + "a": ["1", "2", "3"], + "b": ["1", "2"], + "c": ["a", "b", "c"], + "d": ["s", "1"], + "e": ["0.01", "1"] + } + """ + @test Serde.deser_json(DifferentTuples, exp_str).a == Tuple(("1", "2", "3")) + @test Serde.deser_json(DifferentTuples, exp_str).b == NTuple{2}(("1", "2")) + @test Serde.deser_json(DifferentTuples, exp_str).c == Tuple{String,String,String}(("a", "b", "c")) + @test Serde.deser_json(DifferentTuples, exp_str).d == Tuple{String,Int64}(("s", 1)) + @test Serde.deser_json(DifferentTuples, exp_str).e == Tuple{Float64,Int64}((0.01, 1)) + + struct Tuples + a::Tuple + b::NTuple{3,Int64} + c::Tuple{Int64,String,Int64} + end + + exp_kvs = Dict{String,Any}( + "a" => ("a", 1), + "b" => (1, 2, 3), + "c" => (1, 2, 3), + ) + exp_obj = Tuples(Tuple(("a", 1)), NTuple{3,Int64}((1, 2, 3)), Tuple{Int64,String,Int64}((1, "2", 3))) + @test Serde.deser(Tuples, exp_kvs).a == exp_obj.a + @test Serde.deser(Tuples, exp_kvs).b == exp_obj.b + @test Serde.deser(Tuples, exp_kvs).c == exp_obj.c + end end