Read a JSON with AL- Business Central

 Sample Data

{ "Customer": { "No": "10000", "Address": "192 Market Square", "Address_2": "", "City": "", "County": "NJ", "Country_Region": "US", "Post_Code": "", "Ship-to": [ { "Code": "LEWES ROAD", "Address": "2 Lewes Road", "Address_2": "", "City": "Atlanta", "County": "GA", "Post_Code": "31772" }, { "Code": "PARK ROAD", "Address": "10 Park Road", "Address_2": "", "City": "Atlanta", "County": "GA", "Post_Code": "31772" } ] } }


The example below shows a basic model to provide enough information to get started reading a simple JSON, resembling the file above, with AL for Microsoft Dynamics 365 Business Central using Codeunit 5459 “JSON Management.”

There are many ways to code a solution, and opinion or situation determines the best (including the Json datatypes). Codeunit 5459 “JSON Management” has many methods for working with JSON files. I encourage you to explore the codeunit.

local procedure ReadJSON(JsonObjectText: Text) var Customer: Record Customer; ShiptoAddress: Record "Ship-to Address"; ArrayJSONManagement: Codeunit "JSON Management"; JSONManagement: Codeunit "JSON Management"; ObjectJSONManagement: Codeunit "JSON Management"; i: Integer; CodeText: Text; CustomerJsonObject: Text; JsonArrayText: Text; ShipToJsonObject: Text; begin JSONManagement.InitializeObject(JsonObjectText); if JSONManagement.GetArrayPropertyValueAsStringByName('Customer', CustomerJsonObject) then begin ObjectJSONManagement.InitializeObject(CustomerJsonObject); Customer.Init(); ObjectJSONManagement.GetStringPropertyValueByName('No', CodeText); Customer.Validate("No.", CopyStr(CodeText.ToUpper(), 1, MaxStrLen(Customer."No."))); ObjectJSONManagement.GetStringPropertyValueByName('Address', CodeText); Customer.Validate("Address", CopyStr(CodeText, 1, MaxStrLen(Customer."Address"))); Customer.Insert(); JSONManagement.InitializeObject(CustomerJsonObject); if JSONManagement.GetArrayPropertyValueAsStringByName('Ship-to', JsonArrayText) then begin ArrayJSONManagement.InitializeCollection(JsonArrayText); for i := 0 to ArrayJSONManagement.GetCollectionCount() - 1 do begin ArrayJSONManagement.GetObjectFromCollectionByIndex(ShipToJsonObject, i); ObjectJSONManagement.InitializeObject(ShipToJsonObject); ShiptoAddress.Init(); ShiptoAddress.Validate("Customer No.", Customer."No."); ObjectJSONManagement.GetStringPropertyValueByName('Code', CodeText); ShiptoAddress.Validate("Code", CopyStr(CodeText.ToUpper(), 1, MaxStrLen(ShiptoAddress.Code))); ShiptoAddress.Validate("Address", CopyStr(CodeText, 1, MaxStrLen(ShiptoAddress.Address))); ShiptoAddress.Insert(); end; end; end; end;


No comments:

Post a Comment