Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
367 views
in Technique[技术] by (71.8m points)

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

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.

question from:https://stackoverflow.com/questions/35863103/how-to-load-a-json-file-and-convert-it-to-an-object-of-a-specific-type

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try casting the custom object to FooObject:

$foo = [FooObject](Get-Content 'C:pathoyour.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:pathoyour.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:pathoyour.json' | Out-String | ConvertFrom-Json
$foo = New-Object FooObject
$foo.AA = $json.Foo
$foo.BB = $json.Bar
$foo.CC = $json.Baz

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...