The Dictionary Data Type represents an unordered collection of keys and values and is optimized for fast lookup of values. Each addition to the dictionary consists of a value and its associated key. Every key in a Dictionary must be unique. It is on my list of favorite “new” AL Data Types, and I find it often easier to work with a dictionary than another object type.
In this example, a JSON Object’s value keys (not the array or object keys) are copied into a Dictionary Data Type variable.
procedure JsonObjectValuestoDictionary(JObject: JsonObject; var ObjectDictionary: Dictionary of [Text, Text])
var
IsHandled: Boolean;
JsonToken: JsonToken;
DuplicateKeyErr: label 'Duplicate Key %1', Comment = '%1 Key Name';
ObjectKeys: List of [Text];
JKey: Text;
JValue: Text;
begin
Clear(ObjectDictionary);
OnBeforeJsonObjectValuestoDictionary(JObject, ObjectDictionary, IsHandled);
if IsHandled then
exit;
ObjectKeys := JObject.Keys();
foreach JKey in ObjectKeys do begin
JObject.Get(Jkey, JsonToken);
if JsonToken.IsValue then begin
if ObjectDictionary.ContainsKey(JKey) then
Error(DuplicateKeyErr, JKey);
JsonToken.WriteTo(JValue);
ObjectDictionary.Add(DelChr(JKey, '=', '"'), DelChr(JValue, '=', '"'));
end;
end;
OnAfterJsonObjectValuestoDictionary(JObject, ObjectDictionary);
end;
[BusinessEvent(false)]
local procedure OnAfterJsonObjectValuestoDictionary(JObject: JsonObject; var ObjectDictionary: Dictionary of [Text, Text])
begin
end;
[BusinessEvent(false)]
local procedure OnBeforeJsonObjectValuestoDictionary(JObject: JsonObject; var ObjectDictionary: Dictionary of [Text, Text]; var Handled: Boolean)
begin
end;
You can learn more about Dictionary Data Types in Dynamics 365 Business Central here.
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.