How to load a JSON file and convert it to an object of a specific type?

NonStatic picture NonStatic · Mar 8, 2016 · Viewed 71.2k times · Source

I have a type FooObject and I have a JSON file which was serialized from a FooObject instance. Now I want to use ConvertFrom-Json to load the JSON file to memory and covert the output of the command to a FooObject object, and then use the new object in a cmdlet Set-Bar which only accept FooObject as the parameter type.

But I notice that the output type of ConvertFrom-Json is PSCustomObject and I did not find any way to convert PSCustomObject to FooObject.

Answer

Ansgar Wiechers picture Ansgar Wiechers · Mar 8, 2016

Try casting the custom object to FooObject:

$foo = [FooObject](Get-Content 'C:\path\to\your.json' | Out-String | ConvertFrom-Json)

If that doesn't work, try constructing the FooObject instance with the properties of the input object (provided the class has a constructor like that):

$json = Get-Content 'C:\path\to\your.json' | Out-String | ConvertFrom-Json
$foo = New-Object FooObject ($json.Foo, $json.Bar, $json.Baz)

If that also doesn't work you need to create an empty FooObject instance and update its properties afterwards:

$json = Get-Content 'C:\path\to\your.json' | Out-String | ConvertFrom-Json
$foo = New-Object FooObject
$foo.AA = $json.Foo
$foo.BB = $json.Bar
$foo.CC = $json.Baz