如何加载JSON文件并将其转换为特定类型的对象?

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

我有一个类型 FooObject 和一个 JSON 文件,它是从 FooObject 实例序列化而来的。现在我想使用 ConvertFrom-Json 将 JSON 文件加载到内存并将命令的输出隐藏到 FooObject 对象,然后在 cmdlet Set-Bar 只接受 FooObject 作为参数类型。

但是我注意到 ConvertFrom-Json 的输出类型是 PSCustomObject 并且我没有找到任何方法将 PSCustomObject 转换为 FooObject

尝试将自定义对象转换为 FooObject:

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

如果这不起作用,请尝试使用输入对象的属性构造 FooObject 实例(前提是 class 具有这样的构造函数):

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

如果这也不起作用,您需要创建一个空的 FooObject 实例,然后更新其属性:

$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

基于PowerTip: Convert JSON File to PowerShell Object,您可以进行以下操作:

Get-Content -Raw -Path <jsonFile>.json | ConvertFrom-Json

我知道这是一个旧的 post,但我发现了一种更有效的方法,如果转换不起作用的话。一定要先尝试铸造它。只要您的 class 不包含自定义类型的嵌套集合,转换就会起作用。假设您的 class 如下所示。

class Container 
{
    [string] $Id
    [string] $Name
    [System.Collections.Generic.List[Process]] $Processes
}
class Process
{
    [string] $Id
    [string] $Name
}

ConvertFrom-Json 会将其转换为 [PSCustomObject],但会将 List[Process] 转换为 Object[],这会导致任何转换操作抛出以下异常。

Cannot convert the "System.Object[]" value of type "System.Object[]" to type "System.Collections.Generic.List`1[Process]".

ConvertToFinalInvalidCastException

使用以下命令反序列化此类层次结构。

$serializer = [System.Web.Script.Serialization.JavaScriptSerializer]::new()

$content = $serializer.Deserialize((Get-Content -Path $JsonFilePath), [YourCustomType])

[System.Web.Script.Serialization.JavaScriptSerializer]ConvertFrom-Json 在后台工作的方式。所以,我刚刚创建了一个新的实例,并且能够转换一个多级别(准确地说是四个级别,每个级别都有一个低于它的级别的集合)json 文件进入我的 powershell class 很容易。我也意识到这可以简化为以下内容,但上面更容易阅读。

$content = [System.Web.Script.Serialization.JavaScriptSerializer]::new().Deserialize((Get-Content -Path $JsonFilePath), [YourCustomType])