json - 如何在 Delphi REST Datasnap 中声明 POST 请求?
问题描述
我正在尝试编写一个函数,该函数将使用 JSON 或 URL 中的多个参数在我的数据库中插入信息。
我已经设法创建了一个函数,该函数将信息从我的数据库返回到客户端,但不是相反。我找到的每个示例都说明了如何创建 JSON,但没有说明如何使用 System.JSON (Delphi 10.2) 接收它
这是实际在我的 Datasnap 上工作的 GET 函数的代码示例:
function TDM_Test.DS_getArticles(pStock : String): string;
begin
try
VGOutils.PR_logs('Get all articles from table');
VGOutils.FU_CheckConnect('1234567890');
with VGOutils.SQ_temp1 do
begin
SQL.Clear;
SQL.Add('SELECT code, name, price, seller, departement FROM articles');
SQL.Add('WHERE stock');
ParamByName('stock').AsString := pStock;
VGOutils.SQ_temp1.Open;
end;
GetInvocationMetadata().ResponseCode := 200;
GetInvocationMetadata().ResponseContent :=
VGOutils.PR_JSON(VGOutils.SQ_temp1, ['code', 'name', 'price', 'seller']);
except on E: Exception do
PR_error(E.Message);
end;
VGOutils.PR_Disconnect;
end;
现在我需要客户将新文章发送到INSERT
我的数据库中。
我唯一想不通的是如何声明函数及其参数。
我希望客户端能够以这种正确格式向我发送 JSON
{"article":[{"code":"AAA","name":"car","price" : "10400.90", "sellers" : [{"seller1" : "Automaniac", "seller2" : "Autopro" }]}]}
现在我知道如何TJSONObject.ParseJSONValue()
通过阅读这个JSON RadStudio来解析它
编辑如果这个 JSON 字符串是硬编码的,它可以很好地与 ParseJSONValue 一起工作,但如果字符串是从 URL 中获取的,我的 JSONstring 只包含“]}”,显然没有什么可以解析的。
function TDM_Test.DS_insertArticles(pUrlJsonString: String): string;
// Hardcoded JSON string
jsonString := '{"article":[{"code":"AAA","name":"car","price" : "10400.90", "sellers" : [{"seller1" : "Automaniac", "seller2" : "Autopro" }]}]}';
JSonValue := TJSONObject.ParseJSONValue(jsonString);
// String received in url
jsonString := pUrlJsonString;
JSonValue := TJSONObject.ParseJSONValue(pUrlJsonString);
解决方案
我通过不使用函数的字符串参数而是Custom body
通过传递 JSONObject 来找到我希望它工作的方式。方法是POST
,内容类型是application/JSON
。
function TDM_Test.DS_insertArticles(pUrlJsonObj: TJSONObject): string;
JSonValue := TJSONObject.ParseJSONValue(pUrlJsonObj);
// Retrieve data for database fields
artCode := JSONValue.GetValue<string>('article[0].code');
artName := JSONValue.GetValue<string>('article[0].name');
artPrice := JSONValue.GetValue<string>('article[0].price');
//... Proceed to INSERT SQL with these values
推荐阅读
- javascript - 在什么情况下不会到达 finally 块?
- powershell - 比较单个 PowerShell 数组中的对象
- firebase - 何时必须在 firestore 触发函数中执行 firestore 读取和写入操作或在 api 端点中直接调用 firestore 之间进行选择
- c# - 尝试使用 COM-interop 从 C# 库中附加 vb6 中的对象时,获取“无法将 'Field' 转换为 'Field' 类型(同一类)”
- asp.net-mvc - IIS 默认网站的 ASP.NET Core 3.1 MVC 路由问题
- azure - AD FS 配置
- vuejs2 - 如何摆脱 NuxtJs 中不匹配的 childNodes 与 VNodes
- redux - 是否可以在执行异步操作的类中保留 redux 调度功能?
- reactjs - 在 React 中,第一次出现在页面上时以不同方式呈现组件的最佳方式是什么?
- r-markdown - 您可以将编织的 HTML 输出恢复为 R 中的原始 RMD/代码吗?