简体   繁体   中英

Delphi TRestRequest array parameter

This might be a simple one.

I'm accessing a RESTFul service with Delphi XE6 using RestClient components: TRestClient, TRestRequest, TRestResponse and THTTPBasicAuthenticator.

The service requires parameters which I have no problems adding:

RestReq.Params.AddItem('param1', 'value1');
RestReq.Params.AddItem('param2', 'value2');

With the above code on the server side it looks like:

{
  "param1":"value1",
  "param2":"value2"
}

However, when I need to send a parameter which is an array and I try:

RestReq.Params.AddItem('param1', 'value1');
RestReq.Params.AddItem('param2', 'value2');
RestReq.Params.AddItem('param3', '[v1, v2, v3]');

The service will reject it because the third parameter is not the expected array. Which is correct because it receives:

{
  "param1":"value1",
  "param2":"value2",
  "param3":"[v1,v2,v3]"
}

I know it looks very simple. Have switched RestClient.ContentType, have tried to manipulate the array. Have tried changing the parameter ContentType, Options and guessing the solution is not a game I like to play. So the question would be: Using the RestClient components ¿how can I call my service with the following parameters?

{
  "param1":"value1",
  "param2":"value2",
  "param3":[
    "v1",
    "v2",
    "v3"
  ]
}

In advance, thanks for your time.

Done! It looks like I was doing it the wrong (or complicated) way. The service was expecting a JSON object and I was building it property by property. There is an easier way:

var aParam: TRESTRequestParameter;
begin
  RestReq.Method := rmPOST; {or rmGET, ...}
  aParam := RestReq.Params.AddItem(); //don't care about setting a name for it
  aParam.Value := TJSONObject.ParseJSONValue('{"param1":"value1","param2":"value2","param3":["v1","v2","v3"]}');
  aParam.ContentType := ctAPPLICATION_JSON;
  //set proxy params, resource, etc.
  RestClient.Execute();
end;

And that will do! Thanks all for your comments.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM