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

问题描述 投票:22回答:3

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

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

json powershell deserialization powershell-v3.0
3个回答
25
投票

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

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

如果这不起作用,尝试使用输入对象的属性构造FooObject实例(假设类具有类似的构造函数):

$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

1
投票

从这里:https://blogs.technet.microsoft.com/heyscriptingguy/2014/04/23/powertip-convert-json-file-to-powershell-object/

我发现以下作品很棒:

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

0
投票

我意识到这是一个老帖子,但我找到了一种更有效的方法来做到这一点,如果投射它不起作用。绝对先尝试一下。只要您的类不包含自定义类型的嵌套集合,就可以使用强制转换。假设您的课程如下所示。

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

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

无法将“System.Object []”类型的“System.Object []”值转换为“System.Collections.Generic.List`1 [Process]”类型。

转换最终的InvalidCastException

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

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

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

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

$content = [System.Web.Script.Serialization.JavaScriptSerializer]::new().Deserialize((Get-Content -Path $JsonFilePath), [YourCustomType])
© www.soinside.com 2019 - 2024. All rights reserved.