gpt4 book ai didi

json - TREST请求 : How to add an array as the body of a PUT request

转载 作者:行者123 更新时间:2023-12-03 18:31:31 24 4
gpt4 key购买 nike

我想发送一个 PUT 请求,其中正文包含一个 JSON 对象数组,如下所示:

PUT http://hostname/api/items
[{"ID":1},{"ID":2},...]

使用如下代码,我可以轻松地发送一个正文中包含单个 TJSONObject 的 POST 请求:

req := TRESTRequest.Create(nil);
req.Client := FRESTClient;
req.Method := TRESTRequestMethod.rmPOST;
req.Resource := 'api/items';
req.AddBody(someJSONObject);
req.Execute;

Fiddler 将请求显示为具有正确的内容:

{"ID",1}

但是,如果我使用 PUT 请求并添加一个 TJSONArray 作为正文......

ja := TJSONArray.Create;
for jo in someJSONObjects do
ja.Add(jo);
req.Method := TRESTRequestMethod.rmPUT;
req.AddBody(ja);

Fiddler 将请求显示为有一大堆奇怪的 JSON 内容:

{"elements":{"items":[{"members":{"items":[{"jsonString":{"strBuffer":{"data":["I","D","","","","","","","","","","","","","",""],"length":2,"maxCapacity":2147483647},"owned":true},"jsonValue":{"strBuffer":{"data":["1","","","","","","","","","","","","","","",""],"length":1,"maxCapacity":2147483647},"owned":true},"owned":true}],...

它看起来像是原始内存对象的某种低级序列化,而不是预期的 JSON 数组内容。

知道我做错了什么吗? documentation AddBody 方法上的帮助不是很大。

最佳答案

回答我自己的问题...

AddBody 方法的重载包括:

procedure AddBody(AObject: TJSONObject);
procedure AddBody<T>(AObject: T);

我假设 TJSONArray 派生自 TJSONObject,因此会使用第一个重载,但实际上这两个类都派生自 TJSONValue。因此,在我的案例中没有使用 TJSONObject 重载,而是使用了通用重载,它显然在某种较低级别的序列化方面取得了成功。

由于 TJSONArray 没有直接重载,而且我使用的 API 不期望将 JSON 数组包装在对象中,所以我改为这样做:

req.AddBody(ja.ToJSON, ctAPPLICATION_JSON);

这会将数组序列化为字符串,然后将内容类型指定为 application/json

关于json - TREST请求 : How to add an array as the body of a PUT request,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26048040/

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