From adc236c598c430031758e43348aa62dbb670666a Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Mon, 12 Jul 2021 10:56:33 -0700 Subject: [PATCH] Don't serialize to json ETS properties for DateTime and string types (#15665) --- .../commands/utility/WebCmdlet/JsonObject.cs | 6 ++++++ .../ConvertTo-Json.Tests.ps1 | 15 +++++++++++++++ 2 files changed, 21 insertions(+) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/JsonObject.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/JsonObject.cs index 9f1d2b1c8..526b251b5 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/JsonObject.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/JsonObject.cs @@ -678,6 +678,12 @@ namespace Microsoft.PowerShell.Commands /// The context for the operation. private static void AppendPsProperties(PSObject psObj, IDictionary receiver, int depth, bool isCustomObject, in ConvertToJsonContext context) { + // if the psObj is a DateTime or String type, we don't serialize any extended or adapted properties + if (psObj.BaseObject is string || psObj.BaseObject is DateTime) + { + return; + } + // serialize only Extended and Adapted properties.. PSMemberInfoCollection srcPropertiesToSearch = new PSMemberInfoIntegratingCollection(psObj, diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/ConvertTo-Json.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/ConvertTo-Json.Tests.ps1 index eca46cb4f..c549975b3 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/ConvertTo-Json.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/ConvertTo-Json.Tests.ps1 @@ -131,4 +131,19 @@ Describe 'ConvertTo-Json' -tags "CI" { $p2.psobject.Properties.Remove('nullstr') } } + + It 'Should not serialize ETS properties added to DateTime' { + $date = "2021-06-24T15:54:06.796999-07:00" + $d = [DateTime]::Parse($date) + + # need to use wildcard here due to some systems may be configured with different culture setting showing time in different format + $d | ConvertTo-Json -Compress | Should -BeLike '"2021-06-24T*' + $d | ConvertTo-Json | ConvertFrom-Json | Should -Be $d + } + + It 'Should not serialize ETS properties added to String' { + $text = "Hello there" + $t = Add-Member -InputObject $text -MemberType NoteProperty -Name text -Value $text -PassThru + $t | ConvertTo-Json -Compress | Should -BeExactly "`"$text`"" + } }