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

Non*_*tic 26 powershell json deserialization powershell-3.0

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

但我注意到输出类型ConvertFrom-JsonPSCustomObject和我没有找到任何转换PSCustomObject方式FooObject.

Ans*_*ers 31

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

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

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

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

如果这也不起作用,则需要创建一个空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
Run Code Online (Sandbox Code Playgroud)

  • 您应该使用```Get-Content -Raw'C:\ path\to\your.json'```来加载你的json内容 (4认同)

Pat*_*vay 6

我意识到这是一篇旧帖子,但我找到了一种更有效的方法,如果投射不起作用。一定要先尝试铸造它。只要您的类不包含自定义类型的嵌套集合,转换就会起作用。假设您的类如下所示。

class Container 
{
    [string] $Id
    [string] $Name
    [System.Collections.Generic.List[Process]] $Processes
}
class Process
{
    [string] $Id
    [string] $Name
}
Run Code Online (Sandbox Code Playgroud)

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

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

ConvertToFinalInvalidCastException

使用以下命令反序列化这种类型的层次结构。

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

$content = $serializer.Deserialize((Get-Content -Path $JsonFilePath), [YourCustomType])
Run Code Online (Sandbox Code Playgroud)

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

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


tha*_*Guy 5

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

我发现以下作品很棒:

Get-Content -Raw -Path <jsonFile>.json | ConvertFrom-Json
Run Code Online (Sandbox Code Playgroud)

  • 如果未指定类型,如何将 JSON 转换为_特定_类型? (5认同)
  • 更短:`Get-Content &lt;jsonFile&gt; | 从 Json 转换` (2认同)