【发布时间】:2012-01-15 05:13:34
【问题描述】:
我正在尝试将哈希表转换为 json 对象,以便在具有 powershell 2.0 的 Web 服务中使用。
$testhash = @{
Name = 'John Doe'
Age = 10
Amount = 10.1
MixedItems = (1,2,3,"a")
NestedHash = @{
nestedkey = "nextedvalue"
}
}
function toJson($obj){
$ms = New-Object IO.MemoryStream
$type = $obj.getType()
[Type[]]$types = ($obj | select -expand PsTypeNames | Select -unique) + [type]'System.Management.Automation.PSObject'
$js = New-Object System.Runtime.Serialization.Json.DataContractJsonSerializer $type, $types, ([int]::MaxValue), $false, $null, $false
$js.writeObject($ms, $obj) | out-null
$utf8.GetString( $ms.ToArray(), 0, $ms.Length )
$ms.Dispose() | out-null
}
toJson $testhash
'[{"Key":"Name","Value":"John Doe"},{"Key":"Age","Value":10},{"Key":"Amount","Value":10.1},{"Key":"NestedHash","Value":[{"__type":"KeyValuePairOfanyTypeanyType:#System.Collections.Generic","key":"nestedkey","value":"nextedvalue"}]},{"Key":"MixedItems","Value":[1,2,3,"a"]}]'
我使用DataContractJsonSerializer constructor 的方式应该抑制类型信息,但显然不是。我也对它提取键和值对感到好笑,但我也不希望它这样做。我做错了什么?
【问题讨论】:
标签: .net json powershell powershell-2.0