如何实现Business Central Web服务读取含数组的JSON数据
解决Dynamics 365 Business Central API直接接收JSON数组的BadRequest问题
问题根源
BC的OData API默认强制要求请求体为单个JSON对象,直接传递数组会触发服务端前置校验,返回BadRequest错误(提示"读取JSON阅读器时意外发现'StartArray'节点,期望'StartObject'节点"),请求根本到不了自定义的ReadColorJSON代码逻辑。
可行解决方案
方案1:用包装对象兼容默认校验(推荐)
把原本的数组请求包裹在一个包含Batch字段的顶层对象里,适配OData的默认规则,再在代码中提取数组处理。
请求示例
{ "Batch": "BATCH001", "Colors": [ {"ID": 1, "Name": "Crimson"}, {"ID": 2, "Name": "Navy"} ] }
对应ReadColorJSON代码调整
procedure ReadColorJSON(var JsonInput: JsonObject) var ColorsArray: JsonArray; ColorObj: JsonObject; BatchText: Text; ColorID: Integer; ColorName: Text; begin // 读取Batch标识 JsonInput.Get('Batch', BatchText); // 提取Colors数组 if JsonInput.Get('Colors', ColorsArray) then begin foreach ColorObj in ColorsArray do begin // 解析单个颜色对象字段 ColorObj.Get('ID', ColorID); ColorObj.Get('Name', ColorName); // 这里替换为你的业务处理逻辑,比如写入数据库 // Example: ColorRec.Init(); ColorRec.ID := ColorID; ColorRec.Name := ColorName; ColorRec.Insert(); end; end; end;
方案2:绕开OData校验直接接收数组(适合必须传纯数组的场景)
如果项目要求必须直接传纯JSON数组,可以通过自定义API页面,跳过OData的对象校验,直接读取原始请求体解析。
自定义API页面代码
page 50100 ColorBatchApi { ApiPageType = Custom; Caption = 'Color Batch Import API'; UsageCategory = Administration; ApplicationArea = All; trigger OnOpenPage() var JsonManagement: Codeunit "JSON Management"; JsonArray: JsonArray; ColorObj: JsonObject; RequestBody: Text; ColorID: Integer; ColorName: Text; begin // 获取原始请求体文本 RequestBody := WebRequestHandler.GetRequestBody(); // 解析为JSON数组 JsonManagement.ReadFromText(RequestBody, JsonArray); // 遍历处理每个颜色对象 foreach ColorObj in JsonArray do begin ColorObj.Get('ID', ColorID); ColorObj.Get('Name', ColorName); // 业务处理逻辑 end; end; }
注意:这种方式需要确保API的权限配置正确,请求头
Content-Type必须设为application/json。
内容的提问来源于stack exchange,提问作者kuhi
相关产品推荐
相关产品推荐

