mirror of
https://github.com/aphrody-labs/PowerShell.git
synced 2026-10-17 12:45:47 +00:00
Add support for converting enums as strings in JSON (#4318)
* converting enums as strings support * removed !CORECLR code per @SteveL-MSFT's request
This commit is contained in:
1 parent
ede3aec52e
commit
02c4d34380
2 files changed
+31
No files matched your search
+14
@@ -14,6 +14,7 @@ using Dbg = System.Management.Automation;
|
||||
using System.Management.Automation.Internal;
|
||||
#if CORECLR
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Converters;
|
||||
#else
|
||||
using System.Collections.Specialized;
|
||||
using System.Web.Script.Serialization;
|
||||
@@ -60,6 +61,15 @@ namespace Microsoft.PowerShell.Commands
|
||||
[Parameter]
|
||||
public SwitchParameter Compress { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// gets or sets the EnumsAsStrings property.
|
||||
/// If the EnumsAsStrings property is set to true, enum values will
|
||||
/// be converted to their string equivalent. Otherwise, enum values
|
||||
/// will be converted to their numeric equivalent.
|
||||
/// </summary>
|
||||
[Parameter()]
|
||||
public SwitchParameter EnumsAsStrings { get; set; }
|
||||
|
||||
#endregion parameters
|
||||
|
||||
#region overrides
|
||||
@@ -122,6 +132,10 @@ namespace Microsoft.PowerShell.Commands
|
||||
object preprocessedObject = ProcessValue(objectToProcess, 0);
|
||||
#if CORECLR
|
||||
JsonSerializerSettings jsonSettings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.None, MaxDepth = 1024 };
|
||||
if (EnumsAsStrings)
|
||||
{
|
||||
jsonSettings.Converters.Add(new StringEnumConverter());
|
||||
}
|
||||
if (!Compress)
|
||||
{
|
||||
jsonSettings.Formatting = Formatting.Indented;
|
||||
|
||||
+17
@@ -211,6 +211,23 @@ Describe "Json Tests" -Tags "Feature" {
|
||||
$emptyStringResult = ConvertFrom-Json ""
|
||||
$emptyStringResult | Should Be $null
|
||||
}
|
||||
|
||||
It "Convert enumerated values to Json" {
|
||||
|
||||
$sampleObject = [pscustomobject]@{
|
||||
PSTypeName = 'Test.EnumSample'
|
||||
SampleSimpleEnum = [System.Management.Automation.ActionPreference]::Ignore
|
||||
SampleBitwiseEnum = [System.Management.Automation.CommandTypes]'Alias,Function,Cmdlet'
|
||||
}
|
||||
|
||||
$response4 = ConvertTo-Json -InputObject $sampleObject -Compress
|
||||
$response4 | Should Be '{"SampleSimpleEnum":4,"SampleBitwiseEnum":11}'
|
||||
|
||||
$response4 = ConvertTo-Json -InputObject $sampleObject -Compress -EnumsAsStrings
|
||||
$response4 | Should Be '{"SampleSimpleEnum":"Ignore","SampleBitwiseEnum":"Alias, Function, Cmdlet"}'
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
Context "JsonObject Tests" {
|
||||
|
||||
Reference in new issue
Block a user