json 如何使用 Powershell 访问宁静的网络服务?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4598120/
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 17:42:21  来源:igfitidea点击:

How can I use Powershell to access a restful webservice?

jsonrestpowershell

提问by reconbot

I need to integrate an existing powershell script to update it's status via a restful web service that returns json. I'm a bit new to powershell but I was able to find the System.Net.WebRequest object do something like the following.

我需要集成一个现有的 powershell 脚本,以通过返回 json 的 Restful Web 服务来更新它的状态。我对 powershell 有点陌生,但我能够找到 System.Net.WebRequest 对象执行以下操作。

$a = [System.Net.WebRequest]::Create("http://intranet/service/object/")
$a.Method = "GET"
$a.GetResponse()

which returns a json array of objects

它返回一个 json 对象数组

[ {id:1}, {id:2}] // etc

I'm not sure where to go from here and how to parse this into a native datatype. I'd like to be able to post and delete as well.

我不知道从哪里开始以及如何将其解析为本机数据类型。我也希望能够发布和删除。

Any pointers? And are there any json/rest libraries or command-lets?

任何指针?是否有任何 json/rest 库或命令包?

回答by Dave

What you want is PowerShell 3and its Invoke-RestMethod, ConvertTo-Json, and ConvertFrom-Json cmdlets. Your code will end up looking like:

您需要的是 PowerShell 3及其Invoke-RestMethodConvertTo-JsonConvertFrom-Json cmdlet。您的代码最终将如下所示:

$stuff = invoke-RestMethod -Uri $url -Method Get;

$stuff = invoke-RestMethod -Uri $url -Method Get;

and there shouldn't even be a need to invoke ConvertFrom-Jsonon the resulting $stuff => it's already in a usable non-string format.

甚至不需要在结果 $stuff 上调用ConvertFrom-Json=> 它已经是可用的非字符串格式。

As for POSTs|PUTs, simply use PowerShell hashes and arrays to structure your data and then call ConvertTo-Jsonon it before passing it to invoke-RestMethod or invoke-WebRequest:

至于 POST|PUT,只需使用 PowerShell 哈希和数组来构造数据,然后在将其传递给 invoke-RestMethod 或 invoke-WebRequest 之前对其调用ConvertTo-Json

invoke-WebRequest -Uri $url -ContentType application/json -Method Post -Body $objectConvertedToJson

invoke-WebRequest -Uri $url -ContentType application/json -Method Post -Body $objectConvertedToJson

See http://technet.microsoft.com/en-us/Library/hh849971.aspxfor details.

有关详细信息,请参阅http://technet.microsoft.com/en-us/Library/hh849971.aspx

回答by Victor Haydin

You could use DataContractJsonSerializer, which is a part of standard .Net library.

您可以使用DataContractJsonSerializer,它是标准 .Net 库的一部分。

回答by x0n

@Jaykul wrote a nice set of RESTful functions that are part of his Mindtouch dreamwiki script over here: http://poshcode.org/691

@Jaykul 在这里编写了一组不错的 RESTful 函数,这些函数是他的 Mindtouch dreamwiki 脚本的一部分:http://poshcode.org/691