I'm using the class
keyword in a powershell script.
I want to serialize instances of my custom class, but I observe that $null
members are serialized as ""
instead of null
.
Reproduction:
Class foo{
[string]$X
}
[foo]@{ x = $null } | ConvertTo-Json
$foo = New-Object foo
$foo.X = $null
$foo | ConvertTo-Json
Outputs :
{
"X": ""
}
{
"X": ""
}
But I'm expecting :
{
"X": null
}
{
"X": null
}
As a side note, this works :
@{ X = $null } | ConvertTo-Json
It outputs expected :
{
"X": null
}
Is there a way to fix this ?
PS: if it matters $PSVersionTable
outputs:
Name Value
---- -----
PSVersion 5.1.19041.546
PSEdition Desktop
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0...}
BuildVersion 10.0.19041.546
CLRVersion 4.0.30319.42000
WSManStackVersion 3.0
PSRemotingProtocolVersion 2.3
SerializationVersion 1.1.0.1