[英]How do I create a multidimensional HashMap or Hashtable in JSP / Java and convert it to a JSON object?
[英]How do I correctly convert a HashTable to JSON in PowerShell?
我正在使用 PowerShell 向REST API
发送POST
请求。 请求的正文如下所示:
{
"title": "game result",
"attachments": [{
"image_url": "http://contoso/",
"title": "good work!"
},
{
"fields": [{
"title": "score",
"value": "100"
},
{
"title": "bonus",
"value": "50"
}
]
}
]
}
现在,以下 PowerShell 脚本产生错误的输出:
$fields = @(@{title='score'; value='100'},@{title='bonus'; value='10'})
$fieldsWrap = @{fields=$fields}
#$fieldsWrap | ConvertTo-Json
$attachments = @(@{title='good work!';image_url='http://contoso'},$fieldsWrap)
$body = @{title='game results';attachments=$attachments}
$json = $body | ConvertTo-Json
$json
第 3 行(如果未注释)产生正确的输出,但第 7 行产生:
{
"attachments": [{
"image_url": "http://contoso",
"title": "good work!"
},
{
"fields": "System.Collections.Hashtable System.Collections.Hashtable"
}
],
"title": "game result"
}
它显然写出了HashTable
的类型名称,这是我假设的默认ToString()
实现。
如何获得正确的输出?
ConvertTo-Json cmdlet 有一个-depth
参数,它:
指定包含在 JSON 表示中的包含对象的级别数。 默认值为 2。
因此,您必须增加它:
$body | ConvertTo-Json -Depth 4
这给出了你想要的 JSON 输出:
@{
title = "game result"
attachments = @(
@{
image_url = "http://contoso/"
title = "good work!"
},
@{
fields = @(
@{
title = "score"
value = "100"
},
@{
title = "bonus"
value = "50"
}
)
}
)
} | ConvertTo-Json -Depth 4
不过,如果没有 Martin Brandl 的建议,就不会奏效 :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.