将 PSObject 从 JSON 反序列化为 C# 中的列表

Deserialize PSObject from JSON to a list in C#

我有一个 C# 应用程序可以使用 PowerShell 显示来自 Active Directory 的信息。

class userps
{
    public string Name { get; set; }
    public bool Enabled { get; set; }
}

PSObject[] results = pipeline.Invoke().ToArray();
List<userps> listUserps = new List<userps>();
foreach (PSObject obj in results)
{
     lista = JsonConvert.DeserializeObject<List<userps>>(obj.ToString());
}

如果对象returns数据至少有两个元素,例如:

[
  {
    "Name":"xxx",
    "Enabled":true
  },
  {
    "Name":"yyy",
    "Enabled":true
  }
]

那么一切都好,List.Count = 2。但是,如果它 returns 一个元素:

[
  {
    "Name":"xxx",
    "Enabled":true
  }
]

然后List.Count = 0 但有一个例外:

Newtonsoft.Json.JsonSerializationException: „Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[ConsoleApp1.userps]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object.
JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
Path 'Name', line 2, position 11.”

我该如何解决这个问题,使其既适用于一个元素又适用于多个元素?

您从 PowerShell 命令中获取的对象似乎不是集合,而是在 JSON 中序列化为对象。当命令 returns 只有一个对象而不是列表时,这是 PowerShell 的常见行为。

示例:

Get-Service | ConvertTo-Json

[
    {
        "Name":  "AdobeFlashPlayerUpdateSvc",
        ...
    },  
    {
        "Name":  "ALG",
        ...
    },
    ...
]

Get-Service -Name 'NetLogon' | ConvertTo-Json

{
    "Name":  "NetLogon",
    ...
}

为避免这种情况,请将命令封装在数组构造函数中,并用 InputObject 参数替换管道:

ConvertTo-Json -InputObject @(Get-Service -Name 'NetLogon')

[
    {
        "Name":  "NetLogon",
        ...
    }
]