我正在使用Delphi XE DataSnap REST服务器,并尝试返回JSON序列化对象。我的方法返回到客户端的结果如下:
I'm working with a Delphi XE DataSnap REST server and trying to return a JSON serialized object. The result that my method is returning to the client looks like this:
{"type":"ServerMethodsUnit1.TJSONIssue", "id":1, "fields":{ "FIssueNo":90210, "FTitle":"Beverly Hills...that''s where I want to be", "FKind":"Wishlist" } }格式良好的JSON。
问题在于,当客户端收到消息时,会添加很多东西,看起来像这样:
The problem is that when the message is received by the client, there's a bunch of stuff added to it and it looks like this:
{"result": ["{\"type\":\"ServerMethodsUnit1.TJSONIssue\", \"id\":1, \"fields\":{ \"FIssueNo\":90210, \"FTitle\":\"Beverly Hills...that's where I want to be\", \"FKind\":\"Wishlist\"} } " ] }我要的反斜杠字符和前面的结果 标记。
I'm getting a bunch of backslash characters and that "result" tag in front.
我想知道是否有人知道我为什么要得到这些多余的东西以及如何摆脱它。
I was wondering if anybody knows why I'm getting this extra stuff and how to get rid of it.
推荐答案要摆脱结果 标记,应使用 OnFormatResult TDSHTTPWebDispatcher 事件。特别是值 Handled 。默认情况下, Handled 的值为 false 。如果设置为 true ,则传递给用户的结果将不会包装在结果 JSON对象中。如果为假,则将其包装在该对象中。
To get rid of "result" tag you should use OnFormatResult event of TDSHTTPWebDispatcher. Especialy the value Handled. The value of Handled is false by default. If set to true, then the result passed to the user will not be wrapped in a "result" JSON object. If it is false, then it will be wrapped in this object.
示例。我有这样的代码:
Example. I have code like this:
function TServerMethods1.EchoStringJSON(Value: string): TJSONObject; var JSONObj : TJSONObject; begin JSONObj := TJSONObject.Create; JSONObj.AddPair(TJSONPair.Create('name',Value)); result := JSONObj; end;REST服务响应如下: { result:[{ name: asdfasdf}]}
REST service response looks like this: {"result":[{"name":"asdfasdf"}]}
我添加了 Handled:= true; :
procedure TWebModule1.DSHTTPWebDispatcher1FormatResult(Sender: TObject; var ResultVal: TJSONValue; const Command: TDBXCommand; var Handled: Boolean); begin Handled := true; end;REST服务响应如下: [{ name: asdfasdf }] 。
REST service response looks like this:[{"name":"asdfasdf"}].
仍然有 [] 。因此,我添加了一些其他代码:
Still have "[]". So I add some additional code:
procedure TWebModule1.DSHTTPWebDispatcher1FormatResult(Sender: TObject; var ResultVal: TJSONValue; const Command: TDBXCommand; var Handled: Boolean); var Aux: TJSONValue; begin //remove [] element Aux := ResultVal; ResultVal := TJSONArray(Aux).Items[0]; TJSONArray(Aux).Remove(0); Aux.Free; //we do not need "result" tag Handled := true; end;现在的结果如下: { name: asdfasdf}
PS。在这里找到了答案: REST响应的FormatResult事件
PS. The answer was found here: section FormatResult Event for REST Responses.
更多推荐
Delphi DataSnap框架向JSON消息添加内容
发布评论