JSON (JavaScript Object Notation) is an open standard file format that uses human-readable text to store and transmit data objects consisting of attribute–value pairs and arrays (or other serializable values).
In today’s digital age, the exchange of data between Microsoft Dynamics 365 Business Central and other systems is often necessary. In a previous post, I covered a basic example of creating an XML file with AL. Along with XML files, I am often asked how to generate JSON files. Here is an example of creating a basic JSON file in AL.
The example below demonstrates a basic model to provide enough information to create a simple file; consider it “Getting Started.” There are many ways to code a solution, and opinion or situation determines the best. Within Microsoft Dynamics 365 Business Central, JSON can be processed codeunit 5459 “JSON Management.” I do use this codeunit often and may cover this example using the codeunit in the future.
local procedure CreateJSON(Customer: Record Customer)
var
ShiptoAddress: Record "Ship-to Address";
JArray: JsonArray;
CustObject: JsonObject;
JsonObject: JsonObject;
ShiptoObject: JsonObject;
JsonData: Text;
begin
Clear(JsonObject);
Clear(CustObject);
CustObject.Add('No', Customer."No.");
CustObject.Add('Address', Customer.Address);
CustObject.Add('Address_2', Customer."Address 2");
CustObject.Add('City', Customer.City);
CustObject.Add('County', Customer.County);
CustObject.Add('Country_Region', Customer."Country/Region Code");
CustObject.Add('Post_Code', Customer."Post Code");
ShiptoAddress.SetRange("Customer No.", Customer."No.");
if ShiptoAddress.FindSet() then begin
Clear(JArray);
repeat
Clear(ShiptoObject);
ShiptoObject.Add('Code', ShiptoAddress.Code);
ShiptoObject.Add('Address', ShiptoAddress.Address);
ShiptoObject.Add('Address_2', ShiptoAddress."Address 2");
ShiptoObject.Add('City', ShiptoAddress.City);
ShiptoObject.Add('County', ShiptoAddress.County);
ShiptoObject.Add('Post_Code', ShiptoAddress."Post Code");
JArray.Add(ShiptoObject);
until ShiptoAddress.Next() = 0;
CustObject.Add('Ship-to', JArray);
end;
JsonObject.Add('Customer', CustObject);
JsonObject.WriteTo(JsonData);
end;
The above code creates the JSON file displayed here:
{
"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"
}
]
}
}
Note: The code and information discussed in this article are for informational and demonstration purposes only. This content was created referencing Microsoft Dynamics 365 Business Central 2022 Wave 2 online.