Azure devops 工作项类型 API returns 字符串而不是 JSON

Azure devops Work Item types API returns string instead of JSON

当我尝试通过 PowerShell 获取工作项类型时,我得到一个字符串而不是预期的 JSON。 这是我的 PowerShell 代码:

$Token = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($PAT)"))
$JsonContentType = 'application/json-patch+json'
$Header = @{Authorization = 'Basic ' + $Token;accept=$JsonContentType}
$BaseUri = "https://dev.azure.com/$($Organisation)/"
$Uri = $BaseUri + "$Project/_apis/wit/workitemtypes?api-version=5.1"
$Result = Invoke-RestMethod -Uri $uri -Method GET -Headers $Header
$Result

我也尝试使用较新的 6.0 版本,但它也是 returns 一个字符串而不是 JSON。 其他回复都可以,例如:

$Uri = "https://dev.azure.com/$($Organisation)/_apis/projects?api-version=5.1"
$Projects = Invoke-RestMethod -Uri $Uri -Method get -Headers $Header

这正确 returns JSON,或者如果我请求工作项,我也会得到 JSON。

我不明白这是为什么...

有什么想法吗?

Invoke-Rest-Method 尝试 return PSCustomObject,它不支持没有名称的属性,因此转换失败,您得到纯字符串:

来自Invoke-RestMethod fails to parse JSON response

The problem is that by default, Invoke-RestMethod tries to convert the json to a PSCustomObject. However, PSCustomObject doesn't support a property without a name. In your script, add -AsHashTable to get an object that supports this.

However, I think that a warning instead of an error may be better here and have the resulting object not contain that property by default.

Powershell 6 及更高版本的解决方案

您可以自己将字符串转换为支持空属性的数据结构(如哈希表)。这可以使用 ConvertFrom-Json 方法完成,如下所示

$Token = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($PAT)"))
$Header = @{Authorization = 'Basic ' + $Token}
$BaseUri = "https://dev.azure.com/$($Organization)/"
$Project = "test"
$Uri = $BaseUri + "$Project/_apis/wit/workitemtypes?api-version=5.1"
$Result = Invoke-RestMethod -Uri $uri -Method GET -Headers $Header

# Check if type is string, then convert to a hashtable
if ($Result.GetType().Name -eq "String") {
    $jsonRes = ConvertFrom-Json -AsHashtable -InputObject $Result
} else {
    $jsonRes = $Result
}

$jsonRes

Powershell 5 及以下版本的解决方案

如果您使用的是旧版本的 powershell,您需要自己或使用第三方工具将字符串解析为哈希映射。 (我不知道有任何内置的 cmdlet 至少可以做到这一点)。

一种选择是使用 JavaScriptSerializer .NET class,这是在 Poshstache module 中完成的。该代码在 link 上可用,因此您应该能够查看它并可能对其进行自定义以满足您的需要