我想发送一个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数组内容。
知道我做错了什么吗? <> 3>}对AddBody方法的帮助不大。
答案 0 :(得分:3)
回答我自己的问题......
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
。