|
363 | 363 | @test_throws LoadError eval(:(@omit_empty "not_a_type")) |
364 | 364 | end |
365 | 365 |
|
| 366 | +@testset "@omit_null/@omit_empty parametric types" begin |
| 367 | + # Test that @omit_null on parametric struct definition works for all instantiations |
| 368 | + @omit_null struct OmitNullParametric{T} |
| 369 | + id::Int |
| 370 | + value::Union{Nothing, T} |
| 371 | + end |
| 372 | + |
| 373 | + # Should work for any type parameter, not just a specific one |
| 374 | + @test JSON.json(OmitNullParametric{String}(1, nothing)) == "{\"id\":1}" |
| 375 | + @test JSON.json(OmitNullParametric{String}(1, "test")) == "{\"id\":1,\"value\":\"test\"}" |
| 376 | + @test JSON.json(OmitNullParametric{Int}(1, nothing)) == "{\"id\":1}" |
| 377 | + @test JSON.json(OmitNullParametric{Int}(1, 42)) == "{\"id\":1,\"value\":42}" |
| 378 | + @test JSON.json(OmitNullParametric{Float64}(1, nothing)) == "{\"id\":1}" |
| 379 | + @test JSON.json(OmitNullParametric{Float64}(1, 3.14)) == "{\"id\":1,\"value\":3.14}" |
| 380 | + |
| 381 | + # Verify omit_null can be overridden at callsite |
| 382 | + @test JSON.json(OmitNullParametric{String}(1, nothing); omit_null=false) == "{\"id\":1,\"value\":null}" |
| 383 | + |
| 384 | + # Test that @omit_empty on parametric struct definition works for all instantiations |
| 385 | + @omit_empty struct OmitEmptyParametric{T} |
| 386 | + id::Int |
| 387 | + items::Vector{T} |
| 388 | + end |
| 389 | + |
| 390 | + @test JSON.json(OmitEmptyParametric{String}(1, String[])) == "{\"id\":1}" |
| 391 | + @test JSON.json(OmitEmptyParametric{String}(1, ["a", "b"])) == "{\"id\":1,\"items\":[\"a\",\"b\"]}" |
| 392 | + @test JSON.json(OmitEmptyParametric{Int}(1, Int[])) == "{\"id\":1}" |
| 393 | + @test JSON.json(OmitEmptyParametric{Int}(1, [1, 2, 3])) == "{\"id\":1,\"items\":[1,2,3]}" |
| 394 | + |
| 395 | + # Verify omit_empty can be overridden at callsite |
| 396 | + @test JSON.json(OmitEmptyParametric{String}(1, String[]); omit_empty=false) == "{\"id\":1,\"items\":[]}" |
| 397 | + |
| 398 | + # Test chaining @omit_null with @defaults on parametric type |
| 399 | + @omit_null @defaults struct ChainedParametric{T} |
| 400 | + id::Int = 0 |
| 401 | + value::Union{Nothing, T} = nothing |
| 402 | + end |
| 403 | + |
| 404 | + @test JSON.json(ChainedParametric{String}()) == "{\"id\":0}" |
| 405 | + @test JSON.json(ChainedParametric{Int}()) == "{\"id\":0}" |
| 406 | + @test JSON.json(ChainedParametric{String}(1, "test")) == "{\"id\":1,\"value\":\"test\"}" |
| 407 | +end |
| 408 | + |
366 | 409 | @testset "Buffered IO" begin |
367 | 410 | # Helper function to create large test data |
368 | 411 | function create_large_object(size::Int) |
|
0 commit comments