I am using a Web API 2.0 that gives me the return data as JSON.
The return data from the Web API is objects, which can contain list of objects (List).
In Powershell, after retrieving the data from the Web API, I would like to have the same objects as the Web API does.
How can I easily convert the JSON return data to objects of same class type as the Web API uses?
I know/have access to the classes (DTO classes) from the Web API.
I can get what I want by doing something like this:
public class Class1DTO
{
public int Id { get; set; }
public string Name { get; set; }
public System.Collections.Generic.List Accounts{ get; set; }
}
public class Class2DTO
{
public int Id { get; set; }
public string Blabla{ get; set; }
public string AccountType { get; set; }
}
"@
Add-Type -TypeDefinition $classes
And then cast the psobject to the classes…
But that seems tedious. Is there an easier way?
Classes in PowerShell are only in v5, and they’re not quite up to that level, yet. As you see, you have to kind of manually define them out each time.
However, have you tried just using ConvertFrom-JSON? That should give you a deserialized object that’s as close as possible to the original, excepting for its TypeName, which you can change yourself if need be.