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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35863103/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 18:18:46  来源:igfitidea点击:

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

jsonpowershelldeserializationpowershell-3.0

提问by NonStatic

I have a type FooObjectand I have a JSON file which was serialized from a FooObjectinstance. Now I want to use ConvertFrom-Jsonto load the JSON file to memory and covert the output of the command to a FooObjectobject, and then use the new object in a cmdlet Set-Barwhich only accept FooObjectas the parameter type.

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

But I notice that the output type of ConvertFrom-Jsonis PSCustomObjectand I did not find any way to convert PSCustomObjectto FooObject.

但我注意到输出类型ConvertFrom-JsonPSCustomObject,我没有找到任何方法来转换PSCustomObjectFooObject.

回答by Ansgar Wiechers

Try casting the custom object to FooObject:

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

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

If that doesn't work, try constructing the FooObjectinstance with the properties of the input object (provided the class has a constructor like that):

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

$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 FooObjectinstance and update its properties afterwards:

如果这也不起作用,您需要创建一个空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

回答by thatOneGuy

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

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

I found the following works great :

我发现以下效果很好:

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

回答by Patrick Mcvay

I realize this is an old post, but I found a more efficient way of doing this, if casting it doesn't work. Definitely try casting it first. Casting will work as long as your class doesn't contain nested collections of custom types. Say your class looks like the following.

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

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

ConvertFrom-Json would convert it to a [PSCustomObject] but would make the List[Process] into an Object[] which would cause any cast operation to throw the following exception.

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

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

ConvertToFinalInvalidCastException

Use the following to deserialize this type of hierarchy.

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

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

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

The [System.Web.Script.Serialization.JavaScriptSerializer]is how ConvertFrom-Jsonworks in the background. So, I just created a new instance of that and was able to convert a multi-level (four levels to be exact and each level had a collection of the level below it) json file into my powershell class easily. I also realize that this could be simplified into the following, but it is easier to read above.

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

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