下面是一个PS函数,用来将PS对象转换为NS json.Net对象.
function ConvertTo-NSJson ( $psObject ) {
$json = $psObject | ConvertTo-Json -Compress -Depth 10
$nsJson = [Newtonsoft.Json.Linq.JObject]::Parse( $json )
return $nsJson
}
这里下面是一个小的PS对象进行测试
$psObject = [PSCustomObject] @{
number = 10
text = 'My message'
list = @( 'item1', 'item2', 'item3' )
hash = @{ key1 = 'text value'; key2 = 2; key3 = $true }
}
如果我在命令提示符下运行函数的每一行,我会得到预期的json.Net对象.
PS > $json = $psObject | ConvertTo-Json -Compress -Depth 10
PS > $nsJson = [Newtonsoft.Json.Linq.JObject]::Parse( $json )
PS > $nsjson['text'].Value
My message
PS > $nsjson.Item('text').Value
My message
PS > $nsjson['number'].Value
10
PS > $nsjson.Item('number').Value
10
PS > $nsjson['list'][0].Value
item1
PS > $nsjson.Item('list')[0].Value
item1
PS > $nsjson['hash']['key1'].Value
text value
PS > $nsjson.Item('hash')['key1'].Value
text value
PS >
原始属性的值是可用的,无论获取它们的方式如何.
如果现在我调用函数ConvertTo-NSJson.我也得到一个json.Net对象,但与之前的对象不同.
PS > $nsjson = ConvertTo-NSJson $psobject
PS > $nsjson['text'].Value # return nothing
PS > $nsjson.Item('text').Value # generate exception
GetValueInvocationException: Exception getting "Item": "Cannot convert argument "index", with value: "text", for "get_Item" to type "System.Int32": "Cannot convert value "text" to type "System.Int32". Error: "The input string 'text' was not in a correct format."""
PS > $nsjson.ToString() # shows correct json content
{
"number": 10,
"text": "My message",
"list": [
"item1",
"item2",
"item3"
],
"hash": {
"key3": true,
"key2": 2,
"key1": "text value"
}
}
PS >
原始属性的值不可用. 第一种方法返回空值,第二种方法产生异常. 但是ToString输出显示nsjson对象包含所有属性和值.
我的错误在哪里? 为什么函数返回的json.Net对象没有相同的行为?