3

How can I parse an PSObject instance to a C# POCO model entity?

The PSObject instance is a dynamic object that contains these properties:

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

I have C# POCO model that fits those fields.

Is there a nice way to cast?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Amir Katz
  • 1,027
  • 1
  • 10
  • 24

1 Answers1

9

You either need to convert the PSObject instance to some common representation or iterate over PSObject.Properties and fill the fields of the POCO using reflection.

This simple serialize-deserialize code with Newtosoft.Json implements the first way and may work well for simple cases:

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}");
}

Output:

{"Name":"David","Diff":0.2,"File":"output.txt"}
Name: David
Diff: 0,2
File: output.txt
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Kirill
  • 3,364
  • 2
  • 21
  • 36