diff --git a/src/Writer.jl b/src/Writer.jl index 6ebea04..c1a9ea6 100644 --- a/src/Writer.jl +++ b/src/Writer.jl @@ -22,6 +22,10 @@ end CompositeTypeWrapper(x, syms) = CompositeTypeWrapper(x, collect(syms)) CompositeTypeWrapper(x) = CompositeTypeWrapper(x, propertynames(x)) +struct SingletonTypeWrapper{T} + wrapped::T +end + """ lower(x) @@ -40,11 +44,11 @@ Note that the return value need not be *recursively* lowered—this function may for instance return an `AbstractArray{Any, 1}` whose elements are not JSON primitives. """ -function lower(a) - if nfields(a) > 0 - CompositeTypeWrapper(a) +function lower(a::T) where {T} + if Base.issingletontype(T) + SingletonTypeWrapper(a) else - error("Cannot serialize type $(typeof(a))") + CompositeTypeWrapper(a) end end @@ -287,6 +291,8 @@ function show_json(io::SC, s::CS, x::CompositeTypeWrapper) end_object(io) end +show_json(io::SC, ::CS, x::SingletonTypeWrapper) = show_string(io, x.wrapped) + function show_json(io::SC, s::CS, x::Union{AbstractVector, Tuple}) begin_array(io) for elt in x diff --git a/test/serializer.jl b/test/serializer.jl index 87927fe..fa7399a 100644 --- a/test/serializer.jl +++ b/test/serializer.jl @@ -72,7 +72,11 @@ end # test serializing a type without any fields struct SingletonType end -@test_throws ErrorException json(SingletonType()) +@test json(SingletonType()) == "\"Main.TestSerializer.SingletonType()\"" + +struct ParamSingletonType{T} end +@test json(ParamSingletonType{Float64}()) == "\"Main.TestSerializer.ParamSingletonType{Float64}()\"" + # test printing to stdout let filename = tempname()