将PSObject解析为C#对象

时间:2016-06-27 08:59:12

标签: c# powershell psobject

如何将PSObject解析为C#POCO模型实体。

PSObject是一个包含这些属性的动态对象

@{Name=David;  Diff=0.0268161397964839; File=Output.txt}

我有适合这些领域的C#POCO模型。

有一种不错的演员方式吗?

1 个答案:

答案 0 :(得分:4)

您需要将PSObject转换为某些常用表示形式或迭代PSObject.Properties并使用反射填充POCO字段。

使用Newtosoft.Json的这个简单的序列化 - 反序列化代码实现了第一种方式,可能适用于简单的情况:

public class MyInfo
{
    public string Name { get; set; }
    public double Diff { get; set; }
    public string File { get; set; }
}

static void Main(string[] args)
{
    PSObject obj = PSObject.AsPSObject(new { Name = "David", Diff = 0.2, File = "output.txt" });

    var serialized = JsonConvert.SerializeObject(obj.Properties.ToDictionary(k => k.Name, v => v.Value));
    Console.WriteLine(serialized);

    var deseialized = JsonConvert.DeserializeObject<MyInfo>(serialized);
    Console.WriteLine($"Name: {deseialized.Name}");
    Console.WriteLine($"Diff: {deseialized.Diff}");
    Console.WriteLine($"File: {deseialized.File}");
}

输出:

{"Name":"David","Diff":0.2,"File":"output.txt"}
Name: David
Diff: 0,2
File: output.txt