From 0e3647317c75f1e35b54a407bc6f9501ca765006 Mon Sep 17 00:00:00 2001 From: Josh Bode Date: Tue, 4 Oct 2016 11:00:24 +1100 Subject: [PATCH] Support for `Nullable` and `Char` (#174) * Support for `Nullable` Added `_writejson` method for `Nullable` values. Maps to JSON `null` if value is null. * trying to fix test fail on 0.4 * Added conversion * Added more tests and converted `Char` handling to use `lower` --- src/JSON.jl | 9 +++++++++ test/runtests.jl | 11 +++++++++++ 2 files changed, 20 insertions(+) diff --git a/src/JSON.jl b/src/JSON.jl index afc1de6..ead1196 100644 --- a/src/JSON.jl +++ b/src/JSON.jl @@ -56,6 +56,7 @@ if VERSION < v"0.5.0-dev+2396" lower(f::Function) = "function at $(f.fptr)" end +lower(c::Char) = string(c) lower(d::DataType) = string(d) lower(m::Module) = throw(ArgumentError("cannot serialize Module $m as JSON")) @@ -167,6 +168,14 @@ function _writejson(io::IO, state::State, n::Void) Base.print(io, "null") end +function _writejson(io::IO, state::State, a::Nullable) + if isnull(a) + Base.print(io, "null") + else + _writejson(io, state, get(a)) + end +end + function _writejson(io::IO, state::State, a::Associative) if length(a) == 0 Base.print(io, "{}") diff --git a/test/runtests.jl b/test/runtests.jl index 339531b..f2924d3 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -251,6 +251,17 @@ end @test sprint(JSON.print, [NaN]) == "[null]" @test sprint(JSON.print, [Inf]) == "[null]" +# check Nullables are printed correctly +@test sprint(JSON.print, [Nullable()]) == "[null]" +@test sprint(JSON.print, [Nullable{Int64}()]) == "[null]" +@test sprint(JSON.print, [Nullable{Int64}(Int64(1))]) == "[1]" + +# check Chars +@test json('a') == "\"a\"" +@test json('\\') == "\"\\\\\"" +@test json('\n') == "\"\\n\"" +@test json('🍩') =="\"🍩\"" + # check for issue #163 @test Float32(JSON.parse(json(2.1f-8))) == 2.1f-8