Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.8k views
in Technique[技术] by (71.8m points)

json - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...