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
.
Use the JavaScript function JSON. parse() to convert text into a JavaScript object: const obj = JSON.
We can convert a JSON to Java Object using the readValue() method of ObjectMapper class, this method deserializes a JSON content from given JSON content String.
The load()/loads() method is used for it. If you have used JSON data from another program or obtained as a string format of JSON, then it can easily be deserialized with load()/loads(), which is usually used to load from string, otherwise, the root object is in list or dict. See the following table given below. json.
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
Based on PowerTip: Convert JSON File to PowerShell Object, you can do the following:
Get-Content -Raw -Path <jsonFile>.json | ConvertFrom-Json
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With