[英]Deserialize PSObject from JSON to a list in C#
I have an application in C# to display information from Active Directory using PowerShell. 我在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());
}
If the object returns data of at least two elements, for example: 如果对象返回至少两个元素的数据,例如:
[
{
"Name":"xxx",
"Enabled":true
},
{
"Name":"yyy",
"Enabled":true
}
]
Then everything is fine, List.Count = 2 . 然后一切都很好, List.Count = 2 。 If, however, it returns one element: 但是,如果返回一个元素:
[
{
"Name":"xxx",
"Enabled":true
}
]
Then List.Count = 0 and there is an exception: 然后List.Count = 0 ,有一个例外:
Newtonsoft.Json.JsonSerializationException: „Cannot deserialize the current JSON object (eg {"name":"value"}) into type 'System.Collections.Generic.List`1[ConsoleApp1.userps]' because the type requires a JSON array (eg [1,2,3]) to deserialize correctly. Newtonsoft.Json.JsonSerializationException:“无法反序列化当前JSON对象(例如{“ name”:“ value”})为类型'System.Collections.Generic.List`1 [ConsoleApp1.userps]',因为该类型需要JSON数组(例如[1,2,3])正确反序列化。
To fix this error either change the JSON to a JSON array (eg [1,2,3]) or change the deserialized type so that it is a normal .NET type (eg not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. 要解决此错误,可以将JSON更改为JSON数组(例如[1,2,3]),也可以更改反序列化类型,使其成为普通的.NET类型(例如,不像整数这样的原始类型,也不像这样的集合类型)数组或列表),可以从JSON对象反序列化。
JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object. 还可以将JsonObjectAttribute添加到类型中,以强制其从JSON对象反序列化。
Path 'Name', line 2, position 11.” 路径“名称”,第2行,位置11。”
How do I solve this problem so it would work for one element and also for several? 我该如何解决这个问题,使其对一个元素也可以对几个元素起作用?
It looks like the object you get from your PowerShell command is not a collection and is serialized as an object in JSON. 从PowerShell命令获得的对象似乎不是集合,并且已序列化为JSON中的对象。 It's the common behaviour of PowerShell when a command returns only one object instead of a list. 当命令仅返回一个对象而不是列表时,这是PowerShell的常见行为。
Example: 例:
Get-Service | ConvertTo-Json
[
{
"Name": "AdobeFlashPlayerUpdateSvc",
...
},
{
"Name": "ALG",
...
},
...
]
Get-Service -Name 'NetLogon' | ConvertTo-Json
{
"Name": "NetLogon",
...
}
To avoid this, encapsulate your command in an array constructor and replace the pipe by the InputObject parameter: 为避免这种情况,请将命令封装在数组构造函数中,并用InputObject参数替换管道:
ConvertTo-Json -InputObject @(Get-Service -Name 'NetLogon')
[
{
"Name": "NetLogon",
...
}
]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.