gpt4 book ai didi

c# - 在 PowerShell 上通过 Rest 获取自定义对象

转载 作者:太空宇宙 更新时间:2023-11-03 13:33:18 25 4
gpt4 key购买 nike

我使用 Powershell 版本 3,我想通过 Rest 获取 uri 上的数据作为对象。我使用了 CmdLedt Invoke-RestMehtod:

 Invoke-RestMethod services.odata.org/OData/OData.svc/Advertisements?$format=json

我的输出是:

id       : http://services.odata.org/OData/OData.svc/Advertisements(guid'f89dee73-a
f9f-4cd4-b330-db93c25ff3c7')
category : category
link : {link, link, link}
title :
updated : 2013-10-29T09:06:33Z
author : author
content : content

但我想要一个输出,其中 ID、名称、Airdate 是一个像这样的对象(2 个对象):

Id                                      Name                                    Airdate
-- ---- -------
f89dee73-af9f-4cd4-b330-db93c25ff3c7 Old School Lemonade Store, Retro Style 2012-11-07T00:00:00
db2d2186-1c29-4d1e-88ef-a127f521b9c6 Early morning start, need coffee 2000-02-29T00:00:00

有人可以向我解释如何通过从返回 JSON 的 URI 中获取一个 costum 对象来获得 CmdLedt 吗?

稍后我必须在 C# 代码中使用它从 URI 获取动态对象,它们总是具有不同的结构。因此我需要这个 CmdLet,因为它通常生成动态对象。到目前为止,在 C# 中我的代码:

 var args = new string[] { "http://services.odata.org/OData/OData.svc/?$format=json" };
var command = string.Format("Invoke-RestMethod {0}", args[0]);

var results = InvokeCommand.InvokeScript(command);

最佳答案

我用过 Fiddler比较来自 PowerShell 的请求和来自浏览器的请求。

// PowerShell
GET /OData/OData.svc/Advertisements?=json HTTP/1.1
// Browser
GET /OData/OData.svc/Advertisements?$format=json HTTP/1.1

如您所见,$format 已从 URL 中删除,您将获得 atom+xml 响应(就像请求 http://services.odata.org/OData/OData.svc/Advertisements,因此没有任何 URL 参数):

Content-Type: application/atom+xml;type=feed;charset=utf-8

为了解决这个问题,在使用PowerShell时需要对$进行转义。

试试这个:

$obj = Invoke-RestMethod -uri "http://services.odata.org/OData/OData.svc/Advertisements?`$format=json"
$obj.value

输出(如您所料):

ID                                      Name                                    AirDate
-- ---- -------
f89dee73-af9f-4cd4-b330-db93c25ff3c7 Old School Lemonade Store, Retro Style 2012-11-07T00:00:00
db2d2186-1c29-4d1e-88ef-a127f521b9c6 Early morning start, need coffee 2000-02-29T00:00:00

关于c# - 在 PowerShell 上通过 Rest 获取自定义对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19654092/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com